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