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