]> git.lizzy.rs Git - rust.git/blob - src/matches.rs
7b691bf61006d5a0f67d04d9fdaf1636fd0df9ec
[rust.git] / src / matches.rs
1 //! Format match expression.
2
3 use std::iter::repeat;
4
5 use rustc_ast::{ast, ptr};
6 use rustc_span::{BytePos, Span};
7
8 use crate::comment::{combine_strs_with_missing_comments, rewrite_comment};
9 use crate::config::lists::*;
10 use crate::config::{Config, ControlBraceStyle, IndentStyle, MatchArmLeadingPipe, Version};
11 use crate::expr::{
12     format_expr, is_empty_block, is_simple_block, is_unsafe_block, prefer_next_line, rewrite_cond,
13     ExprType, RhsTactics,
14 };
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;
20 use crate::utils::{
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,
23 };
24
25 /// A simple wrapper type against `ast::Arm`. Used inside `write_list()`.
26 struct ArmWrapper<'a> {
27     arm: &'a ast::Arm,
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`.
30     is_last: bool,
31     /// Holds a byte position of `|` at the beginning of the arm pattern, if available.
32     beginning_vert: Option<BytePos>,
33 }
34
35 impl<'a> ArmWrapper<'a> {
36     fn new(arm: &'a ast::Arm, is_last: bool, beginning_vert: Option<BytePos>) -> ArmWrapper<'a> {
37         ArmWrapper {
38             arm,
39             is_last,
40             beginning_vert,
41         }
42     }
43 }
44
45 impl<'a> Spanned for ArmWrapper<'a> {
46     fn span(&self) -> Span {
47         if let Some(lo) = self.beginning_vert {
48             let lo = std::cmp::min(lo, self.arm.span().lo());
49             mk_sp(lo, self.arm.span().hi())
50         } else {
51             self.arm.span()
52         }
53     }
54 }
55
56 impl<'a> Rewrite for ArmWrapper<'a> {
57     fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
58         rewrite_match_arm(
59             context,
60             self.arm,
61             shape,
62             self.is_last,
63             self.beginning_vert.is_some(),
64         )
65     }
66 }
67
68 pub(crate) fn rewrite_match(
69     context: &RewriteContext<'_>,
70     cond: &ast::Expr,
71     arms: &[ast::Arm],
72     shape: Shape,
73     span: Span,
74     attrs: &[ast::Attribute],
75 ) -> Option<String> {
76     // Do not take the rhs overhead from the upper expressions into account
77     // when rewriting match condition.
78     let cond_shape = Shape {
79         width: context.budget(shape.used_width()),
80         ..shape
81     };
82     // 6 = `match `
83     let cond_shape = match context.config.indent_style() {
84         IndentStyle::Visual => cond_shape.shrink_left(6)?,
85         IndentStyle::Block => cond_shape.offset_left(6)?,
86     };
87     let cond_str = cond.rewrite(context, cond_shape)?;
88     let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
89     let block_sep = match context.config.control_brace_style() {
90         ControlBraceStyle::AlwaysNextLine => alt_block_sep,
91         _ if last_line_extendable(&cond_str) => " ",
92         // 2 = ` {`
93         _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => alt_block_sep,
94         _ => " ",
95     };
96
97     let nested_indent_str = shape
98         .indent
99         .block_indent(context.config)
100         .to_string(context.config);
101     // Inner attributes.
102     let inner_attrs = &inner_attributes(attrs);
103     let inner_attrs_str = if inner_attrs.is_empty() {
104         String::new()
105     } else {
106         inner_attrs
107             .rewrite(context, shape)
108             .map(|s| format!("{}{}\n", nested_indent_str, s))?
109     };
110
111     let open_brace_pos = if inner_attrs.is_empty() {
112         let hi = if arms.is_empty() {
113             span.hi()
114         } else {
115             arms[0].span().lo()
116         };
117         context
118             .snippet_provider
119             .span_after(mk_sp(cond.span.hi(), hi), "{")
120     } else {
121         inner_attrs[inner_attrs.len() - 1].span.hi()
122     };
123
124     if arms.is_empty() {
125         let snippet = context.snippet(mk_sp(open_brace_pos, span.hi() - BytePos(1)));
126         if snippet.trim().is_empty() {
127             Some(format!("match {} {{}}", cond_str))
128         } else {
129             // Empty match with comments or inner attributes? We are not going to bother, sorry ;)
130             Some(context.snippet(span).to_owned())
131         }
132     } else {
133         let span_after_cond = mk_sp(cond.span.hi(), span.hi());
134         Some(format!(
135             "match {}{}{{\n{}{}{}\n{}}}",
136             cond_str,
137             block_sep,
138             inner_attrs_str,
139             nested_indent_str,
140             rewrite_match_arms(context, arms, shape, span_after_cond, open_brace_pos)?,
141             shape.indent.to_string(context.config),
142         ))
143     }
144 }
145
146 fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
147     if is_last && config.trailing_comma() == SeparatorTactic::Never {
148         ""
149     } else if config.match_block_trailing_comma() {
150         ","
151     } else if let ast::ExprKind::Block(ref block, _) = body.kind {
152         if let ast::BlockCheckMode::Default = block.rules {
153             ""
154         } else {
155             ","
156         }
157     } else {
158         ","
159     }
160 }
161
162 /// Collect a byte position of the beginning `|` for each arm, if available.
163 fn collect_beginning_verts(
164     context: &RewriteContext<'_>,
165     arms: &[ast::Arm],
166     span: Span,
167 ) -> Vec<Option<BytePos>> {
168     let mut beginning_verts = Vec::with_capacity(arms.len());
169     let mut lo = context.snippet_provider.span_after(span, "{");
170     for arm in arms {
171         let hi = arm.pat.span.lo();
172         let missing_span = mk_sp(lo, hi);
173         beginning_verts.push(context.snippet_provider.opt_span_before(missing_span, "|"));
174         lo = arm.span().hi();
175     }
176     beginning_verts
177 }
178
179 fn rewrite_match_arms(
180     context: &RewriteContext<'_>,
181     arms: &[ast::Arm],
182     shape: Shape,
183     span: Span,
184     open_brace_pos: BytePos,
185 ) -> Option<String> {
186     let arm_shape = shape
187         .block_indent(context.config.tab_spaces())
188         .with_max_width(context.config);
189
190     let arm_len = arms.len();
191     let is_last_iter = repeat(false)
192         .take(arm_len.saturating_sub(1))
193         .chain(repeat(true));
194     let beginning_verts = collect_beginning_verts(context, arms, span);
195     let items = itemize_list(
196         context.snippet_provider,
197         arms.iter()
198             .zip(is_last_iter)
199             .zip(beginning_verts.into_iter())
200             .map(|((arm, is_last), beginning_vert)| ArmWrapper::new(arm, is_last, beginning_vert)),
201         "}",
202         "|",
203         |arm| arm.span().lo(),
204         |arm| arm.span().hi(),
205         |arm| arm.rewrite(context, arm_shape),
206         open_brace_pos,
207         span.hi(),
208         false,
209     );
210     let arms_vec: Vec<_> = items.collect();
211     // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
212     let fmt = ListFormatting::new(arm_shape, context.config)
213         .separator("")
214         .preserve_newline(true);
215
216     write_list(&arms_vec, &fmt)
217 }
218
219 fn rewrite_match_arm(
220     context: &RewriteContext<'_>,
221     arm: &ast::Arm,
222     shape: Shape,
223     is_last: bool,
224     has_leading_pipe: bool,
225 ) -> Option<String> {
226     let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
227         if contains_skip(&arm.attrs) {
228             let (_, body) = flatten_arm_body(context, &arm.body, None);
229             // `arm.span()` does not include trailing comma, add it manually.
230             return Some(format!(
231                 "{}{}",
232                 context.snippet(arm.span()),
233                 arm_comma(context.config, body, is_last),
234             ));
235         }
236         let missing_span = mk_sp(arm.attrs[arm.attrs.len() - 1].span.hi(), arm.pat.span.lo());
237         (missing_span, arm.attrs.rewrite(context, shape)?)
238     } else {
239         (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
240     };
241
242     // Leading pipe offset
243     // 2 = `| `
244     let (pipe_offset, pipe_str) = match context.config.match_arm_leading_pipes() {
245         MatchArmLeadingPipe::Never => (0, ""),
246         MatchArmLeadingPipe::Preserve if !has_leading_pipe => (0, ""),
247         MatchArmLeadingPipe::Preserve | MatchArmLeadingPipe::Always => (2, "| "),
248     };
249
250     // Patterns
251     // 5 = ` => {`
252     let pat_shape = shape.sub_width(5)?.offset_left(pipe_offset)?;
253     let pats_str = arm.pat.rewrite(context, pat_shape)?;
254
255     // Guard
256     let block_like_pat = trimmed_last_line_width(&pats_str) <= context.config.tab_spaces();
257     let new_line_guard = pats_str.contains('\n') && !block_like_pat;
258     let guard_str = rewrite_guard(
259         context,
260         &arm.guard,
261         shape,
262         trimmed_last_line_width(&pats_str),
263         new_line_guard,
264     )?;
265
266     let lhs_str = combine_strs_with_missing_comments(
267         context,
268         &attrs_str,
269         &format!("{}{}{}", pipe_str, pats_str, guard_str),
270         missing_span,
271         shape,
272         false,
273     )?;
274
275     let arrow_span = mk_sp(arm.pat.span.hi(), arm.body.span().lo());
276     rewrite_match_body(
277         context,
278         &arm.body,
279         &lhs_str,
280         shape,
281         guard_str.contains('\n'),
282         arrow_span,
283         is_last,
284     )
285 }
286
287 fn block_can_be_flattened<'a>(
288     context: &RewriteContext<'_>,
289     expr: &'a ast::Expr,
290 ) -> Option<&'a ast::Block> {
291     match expr.kind {
292         ast::ExprKind::Block(ref block, _)
293             if !is_unsafe_block(block)
294                 && !context.inside_macro()
295                 && is_simple_block(context, block, Some(&expr.attrs)) =>
296         {
297             Some(&*block)
298         }
299         _ => None,
300     }
301 }
302
303 // (extend, body)
304 // @extend: true if the arm body can be put next to `=>`
305 // @body: flattened body, if the body is block with a single expression
306 fn flatten_arm_body<'a>(
307     context: &'a RewriteContext<'_>,
308     body: &'a ast::Expr,
309     opt_shape: Option<Shape>,
310 ) -> (bool, &'a ast::Expr) {
311     let can_extend =
312         |expr| !context.config.force_multiline_blocks() && can_flatten_block_around_this(expr);
313
314     if let Some(ref block) = block_can_be_flattened(context, body) {
315         if let ast::StmtKind::Expr(ref expr) = block.stmts[0].kind {
316             if let ast::ExprKind::Block(..) = expr.kind {
317                 flatten_arm_body(context, expr, None)
318             } else {
319                 let cond_becomes_muti_line = opt_shape
320                     .and_then(|shape| rewrite_cond(context, expr, shape))
321                     .map_or(false, |cond| cond.contains('\n'));
322                 if cond_becomes_muti_line {
323                     (false, &*body)
324                 } else {
325                     (can_extend(expr), &*expr)
326                 }
327             }
328         } else {
329             (false, &*body)
330         }
331     } else {
332         (can_extend(body), &*body)
333     }
334 }
335
336 fn rewrite_match_body(
337     context: &RewriteContext<'_>,
338     body: &ptr::P<ast::Expr>,
339     pats_str: &str,
340     shape: Shape,
341     has_guard: bool,
342     arrow_span: Span,
343     is_last: bool,
344 ) -> Option<String> {
345     let (extend, body) = flatten_arm_body(
346         context,
347         body,
348         shape.offset_left(extra_offset(pats_str, shape) + 4),
349     );
350     let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block, _) = body.kind {
351         (true, is_empty_block(context, block, Some(&body.attrs)))
352     } else {
353         (false, false)
354     };
355
356     let comma = arm_comma(context.config, body, is_last);
357     let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
358
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,
362             _ => " ",
363         };
364
365         Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
366     };
367
368     let next_line_indent = if !is_block || is_empty_block {
369         shape.indent.block_indent(context.config)
370     } else {
371         shape.indent
372     };
373
374     let forbid_same_line =
375         (has_guard && pats_str.contains('\n') && !is_empty_block) || !body.attrs.is_empty();
376
377     // Look for comments between `=>` and the start of the body.
378     let arrow_comment = {
379         let arrow_snippet = context.snippet(arrow_span).trim();
380         // search for the arrow starting from the end of the snippet since there may be a match
381         // expression within the guard
382         let arrow_index = arrow_snippet.rfind("=>").unwrap();
383         // 2 = `=>`
384         let comment_str = arrow_snippet[arrow_index + 2..].trim();
385         if comment_str.is_empty() {
386             String::new()
387         } else {
388             rewrite_comment(comment_str, false, shape, &context.config)?
389         }
390     };
391
392     let combine_next_line_body = |body_str: &str| {
393         let nested_indent_str = next_line_indent.to_string_with_newline(context.config);
394
395         if is_block {
396             let mut result = pats_str.to_owned();
397             result.push_str(" =>");
398             if !arrow_comment.is_empty() {
399                 result.push_str(&nested_indent_str);
400                 result.push_str(&arrow_comment);
401             }
402             result.push_str(&nested_indent_str);
403             result.push_str(&body_str);
404             return Some(result);
405         }
406
407         let indent_str = shape.indent.to_string_with_newline(context.config);
408         let (body_prefix, body_suffix) =
409             if context.config.match_arm_blocks() && !context.inside_macro() {
410                 let comma = if context.config.match_block_trailing_comma() {
411                     ","
412                 } else {
413                     ""
414                 };
415                 let semicolon = if context.config.version() == Version::One {
416                     ""
417                 } else {
418                     if semicolon_for_expr(context, body) {
419                         ";"
420                     } else {
421                         ""
422                     }
423                 };
424                 ("{", format!("{}{}}}{}", semicolon, indent_str, comma))
425             } else {
426                 ("", String::from(","))
427             };
428
429         let block_sep = match context.config.control_brace_style() {
430             ControlBraceStyle::AlwaysNextLine => format!("{}{}", alt_block_sep, body_prefix),
431             _ if body_prefix.is_empty() => "".to_owned(),
432             _ if forbid_same_line || !arrow_comment.is_empty() => {
433                 format!("{}{}", alt_block_sep, body_prefix)
434             }
435             _ => format!(" {}", body_prefix),
436         } + &nested_indent_str;
437
438         let mut result = pats_str.to_owned();
439         result.push_str(" =>");
440         if !arrow_comment.is_empty() {
441             result.push_str(&indent_str);
442             result.push_str(&arrow_comment);
443         }
444         result.push_str(&block_sep);
445         result.push_str(&body_str);
446         result.push_str(&body_suffix);
447         Some(result)
448     };
449
450     // Let's try and get the arm body on the same line as the condition.
451     // 4 = ` => `.len()
452     let orig_body_shape = shape
453         .offset_left(extra_offset(pats_str, shape) + 4)
454         .and_then(|shape| shape.sub_width(comma.len()));
455     let orig_body = if forbid_same_line || !arrow_comment.is_empty() {
456         None
457     } else if let Some(body_shape) = orig_body_shape {
458         let rewrite = nop_block_collapse(
459             format_expr(body, ExprType::Statement, context, body_shape),
460             body_shape.width,
461         );
462
463         match rewrite {
464             Some(ref body_str)
465                 if is_block
466                     || (!body_str.contains('\n')
467                         && unicode_str_width(body_str) <= body_shape.width) =>
468             {
469                 return combine_orig_body(body_str);
470             }
471             _ => rewrite,
472         }
473     } else {
474         None
475     };
476     let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
477
478     // Try putting body on the next line and see if it looks better.
479     let next_line_body_shape = Shape::indented(next_line_indent, context.config);
480     let next_line_body = nop_block_collapse(
481         format_expr(body, ExprType::Statement, context, next_line_body_shape),
482         next_line_body_shape.width,
483     );
484     match (orig_body, next_line_body) {
485         (Some(ref orig_str), Some(ref next_line_str))
486             if prefer_next_line(orig_str, next_line_str, RhsTactics::Default) =>
487         {
488             combine_next_line_body(next_line_str)
489         }
490         (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
491             combine_orig_body(orig_str)
492         }
493         (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
494             combine_next_line_body(next_line_str)
495         }
496         (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
497         (None, None) => None,
498         (Some(ref orig_str), _) => combine_orig_body(orig_str),
499     }
500 }
501
502 // The `if ...` guard on a match arm.
503 fn rewrite_guard(
504     context: &RewriteContext<'_>,
505     guard: &Option<ptr::P<ast::Expr>>,
506     shape: Shape,
507     // The amount of space used up on this line for the pattern in
508     // the arm (excludes offset).
509     pattern_width: usize,
510     multiline_pattern: bool,
511 ) -> Option<String> {
512     if let Some(ref guard) = *guard {
513         // First try to fit the guard string on the same line as the pattern.
514         // 4 = ` if `, 5 = ` => {`
515         let cond_shape = shape
516             .offset_left(pattern_width + 4)
517             .and_then(|s| s.sub_width(5));
518         if !multiline_pattern {
519             if let Some(cond_shape) = cond_shape {
520                 if let Some(cond_str) = guard.rewrite(context, cond_shape) {
521                     if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
522                         return Some(format!(" if {}", cond_str));
523                     }
524                 }
525             }
526         }
527
528         // Not enough space to put the guard after the pattern, try a newline.
529         // 3 = `if `, 5 = ` => {`
530         let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
531             .offset_left(3)
532             .and_then(|s| s.sub_width(5));
533         if let Some(cond_shape) = cond_shape {
534             if let Some(cond_str) = guard.rewrite(context, cond_shape) {
535                 return Some(format!(
536                     "{}if {}",
537                     cond_shape.indent.to_string_with_newline(context.config),
538                     cond_str
539                 ));
540             }
541         }
542
543         None
544     } else {
545         Some(String::new())
546     }
547 }
548
549 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
550     debug!("nop_block_collapse {:?} {}", block_str, budget);
551     block_str.map(|block_str| {
552         if block_str.starts_with('{')
553             && budget >= 2
554             && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
555         {
556             String::from("{}")
557         } else {
558             block_str
559         }
560     })
561 }
562
563 fn can_flatten_block_around_this(body: &ast::Expr) -> bool {
564     match body.kind {
565         // We do not allow `if` to stay on the same line, since we could easily mistake
566         // `pat => if cond { ... }` and `pat if cond => { ... }`.
567         ast::ExprKind::If(..) => false,
568         // We do not allow collapsing a block around expression with condition
569         // to avoid it being cluttered with match arm.
570         ast::ExprKind::ForLoop(..) | ast::ExprKind::While(..) => false,
571         ast::ExprKind::Loop(..)
572         | ast::ExprKind::Match(..)
573         | ast::ExprKind::Block(..)
574         | ast::ExprKind::Closure(..)
575         | ast::ExprKind::Array(..)
576         | ast::ExprKind::Call(..)
577         | ast::ExprKind::MethodCall(..)
578         | ast::ExprKind::MacCall(..)
579         | ast::ExprKind::Struct(..)
580         | ast::ExprKind::Tup(..) => true,
581         ast::ExprKind::AddrOf(_, _, ref expr)
582         | ast::ExprKind::Box(ref expr)
583         | ast::ExprKind::Try(ref expr)
584         | ast::ExprKind::Unary(_, ref expr)
585         | ast::ExprKind::Index(ref expr, _)
586         | ast::ExprKind::Cast(ref expr, _) => can_flatten_block_around_this(expr),
587         _ => false,
588     }
589 }