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