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