]> git.lizzy.rs Git - rust.git/blob - src/matches.rs
c179efc3963e7a42796a623d77ebf7d8539207cf
[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 config::lists::*;
16 use syntax::codemap::{BytePos, Span};
17 use syntax::{ast, ptr};
18
19 use codemap::SpanUtils;
20 use comment::combine_strs_with_missing_comments;
21 use config::{Config, ControlBraceStyle, IndentStyle};
22 use expr::{
23     format_expr, is_empty_block, is_simple_block, is_unsafe_block, prefer_next_line,
24     rewrite_multiple_patterns, ExprType, RhsTactics, ToExpr,
25 };
26 use lists::{itemize_list, write_list, ListFormatting};
27 use rewrite::{Rewrite, RewriteContext};
28 use shape::Shape;
29 use spanned::Spanned;
30 use utils::{
31     contains_skip, extra_offset, first_line_width, inner_attributes, last_line_extendable, mk_sp,
32     ptr_vec_to_ref_vec, 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, self.beginning_vert)
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     let fmt = ListFormatting {
219         tactic: DefinitiveListTactic::Vertical,
220         // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
221         separator: "",
222         trailing_separator: SeparatorTactic::Never,
223         separator_place: SeparatorPlace::Back,
224         shape: arm_shape,
225         ends_with_newline: true,
226         preserve_newline: true,
227         nested: false,
228         config: context.config,
229     };
230
231     write_list(&arms_vec, &fmt)
232 }
233
234 fn rewrite_match_arm(
235     context: &RewriteContext,
236     arm: &ast::Arm,
237     shape: Shape,
238     is_last: bool,
239     beginning_vert: Option<BytePos>,
240 ) -> Option<String> {
241     let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
242         if contains_skip(&arm.attrs) {
243             let (_, body) = flatten_arm_body(context, &arm.body);
244             // `arm.span()` does not include trailing comma, add it manually.
245             return Some(format!(
246                 "{}{}",
247                 context.snippet(arm.span()),
248                 arm_comma(context.config, body, is_last),
249             ));
250         }
251         let missing_span = mk_sp(
252             arm.attrs[arm.attrs.len() - 1].span.hi(),
253             arm.pats[0].span.lo(),
254         );
255         (missing_span, arm.attrs.rewrite(context, shape)?)
256     } else {
257         (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
258     };
259     let pats_str = rewrite_match_pattern(
260         context,
261         &ptr_vec_to_ref_vec(&arm.pats),
262         &arm.guard,
263         beginning_vert.is_some(),
264         shape,
265     ).and_then(|pats_str| {
266         combine_strs_with_missing_comments(
267             context,
268             &attrs_str,
269             &pats_str,
270             missing_span,
271             shape,
272             false,
273         )
274     })?;
275     rewrite_match_body(
276         context,
277         &arm.body,
278         &pats_str,
279         shape,
280         arm.guard.is_some(),
281         is_last,
282     )
283 }
284
285 fn rewrite_match_pattern(
286     context: &RewriteContext,
287     pats: &[&ast::Pat],
288     guard: &Option<ptr::P<ast::Expr>>,
289     has_beginning_vert: bool,
290     shape: Shape,
291 ) -> Option<String> {
292     // Patterns
293     // 5 = ` => {`
294     // 2 = `| `
295     let pat_shape = shape
296         .sub_width(5)?
297         .offset_left(if has_beginning_vert { 2 } else { 0 })?;
298     let pats_str = rewrite_multiple_patterns(context, pats, pat_shape)?;
299     let beginning_vert = if has_beginning_vert { "| " } else { "" };
300
301     // Guard
302     let guard_str = rewrite_guard(context, guard, shape, trimmed_last_line_width(&pats_str))?;
303
304     Some(format!("{}{}{}", beginning_vert, pats_str, guard_str))
305 }
306
307 // (extend, body)
308 // @extend: true if the arm body can be put next to `=>`
309 // @body: flattened body, if the body is block with a single expression
310 fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
311     match body.node {
312         ast::ExprKind::Block(ref block, _)
313             if !is_unsafe_block(block)
314                 && is_simple_block(block, Some(&body.attrs), context.codemap) =>
315         {
316             if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
317                 (
318                     !context.config.force_multiline_blocks() && can_flatten_block_around_this(expr),
319                     &*expr,
320                 )
321             } else {
322                 (false, &*body)
323             }
324         }
325         _ => (
326             !context.config.force_multiline_blocks() && body.can_be_overflowed(context, 1),
327             &*body,
328         ),
329     }
330 }
331
332 fn rewrite_match_body(
333     context: &RewriteContext,
334     body: &ptr::P<ast::Expr>,
335     pats_str: &str,
336     shape: Shape,
337     has_guard: bool,
338     is_last: bool,
339 ) -> Option<String> {
340     let (extend, body) = flatten_arm_body(context, body);
341     let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block, _) = body.node {
342         (
343             true,
344             is_empty_block(block, Some(&body.attrs), context.codemap),
345         )
346     } else {
347         (false, false)
348     };
349
350     let comma = arm_comma(context.config, body, is_last);
351     let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
352
353     let combine_orig_body = |body_str: &str| {
354         let block_sep = match context.config.control_brace_style() {
355             ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
356             _ => " ",
357         };
358
359         Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
360     };
361
362     let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
363     let next_line_indent = if !is_block || is_empty_block {
364         shape.indent.block_indent(context.config)
365     } else {
366         shape.indent
367     };
368     let combine_next_line_body = |body_str: &str| {
369         if is_block {
370             return Some(format!(
371                 "{} =>{}{}",
372                 pats_str,
373                 next_line_indent.to_string_with_newline(context.config),
374                 body_str
375             ));
376         }
377
378         let indent_str = shape.indent.to_string_with_newline(context.config);
379         let nested_indent_str = next_line_indent.to_string_with_newline(context.config);
380         let (body_prefix, body_suffix) = if context.config.match_arm_blocks() {
381             let comma = if context.config.match_block_trailing_comma() {
382                 ","
383             } else {
384                 ""
385             };
386             ("{", format!("{}}}{}", indent_str, comma))
387         } else {
388             ("", String::from(","))
389         };
390
391         let block_sep = match context.config.control_brace_style() {
392             ControlBraceStyle::AlwaysNextLine => format!("{}{}", alt_block_sep, body_prefix),
393             _ if body_prefix.is_empty() => "".to_owned(),
394             _ if forbid_same_line => format!("{}{}", alt_block_sep, body_prefix),
395             _ => format!(" {}", body_prefix),
396         } + &nested_indent_str;
397
398         Some(format!(
399             "{} =>{}{}{}",
400             pats_str, block_sep, body_str, body_suffix
401         ))
402     };
403
404     // Let's try and get the arm body on the same line as the condition.
405     // 4 = ` => `.len()
406     let orig_body_shape = shape
407         .offset_left(extra_offset(pats_str, shape) + 4)
408         .and_then(|shape| shape.sub_width(comma.len()));
409     let orig_body = if let Some(body_shape) = orig_body_shape {
410         let rewrite = nop_block_collapse(
411             format_expr(body, ExprType::Statement, context, body_shape),
412             body_shape.width,
413         );
414
415         match rewrite {
416             Some(ref body_str)
417                 if !forbid_same_line
418                     && (is_block
419                         || (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
420             {
421                 return combine_orig_body(body_str);
422             }
423             _ => rewrite,
424         }
425     } else {
426         None
427     };
428     let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
429
430     // Try putting body on the next line and see if it looks better.
431     let next_line_body_shape = Shape::indented(next_line_indent, context.config);
432     let next_line_body = nop_block_collapse(
433         format_expr(body, ExprType::Statement, context, next_line_body_shape),
434         next_line_body_shape.width,
435     );
436     match (orig_body, next_line_body) {
437         (Some(ref orig_str), Some(ref next_line_str))
438             if forbid_same_line
439                 || prefer_next_line(orig_str, next_line_str, RhsTactics::Default) =>
440         {
441             combine_next_line_body(next_line_str)
442         }
443         (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
444             combine_orig_body(orig_str)
445         }
446         (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
447             combine_next_line_body(next_line_str)
448         }
449         (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
450         (None, None) => None,
451         (Some(ref orig_str), _) => combine_orig_body(orig_str),
452     }
453 }
454
455 // The `if ...` guard on a match arm.
456 fn rewrite_guard(
457     context: &RewriteContext,
458     guard: &Option<ptr::P<ast::Expr>>,
459     shape: Shape,
460     // The amount of space used up on this line for the pattern in
461     // the arm (excludes offset).
462     pattern_width: usize,
463 ) -> Option<String> {
464     if let Some(ref guard) = *guard {
465         // First try to fit the guard string on the same line as the pattern.
466         // 4 = ` if `, 5 = ` => {`
467         let cond_shape = shape
468             .offset_left(pattern_width + 4)
469             .and_then(|s| s.sub_width(5));
470         if let Some(cond_shape) = cond_shape {
471             if let Some(cond_str) = guard.rewrite(context, cond_shape) {
472                 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
473                     return Some(format!(" if {}", cond_str));
474                 }
475             }
476         }
477
478         // Not enough space to put the guard after the pattern, try a newline.
479         // 3 = `if `, 5 = ` => {`
480         let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
481             .offset_left(3)
482             .and_then(|s| s.sub_width(5));
483         if let Some(cond_shape) = cond_shape {
484             if let Some(cond_str) = guard.rewrite(context, cond_shape) {
485                 return Some(format!(
486                     "{}if {}",
487                     cond_shape.indent.to_string_with_newline(context.config),
488                     cond_str
489                 ));
490             }
491         }
492
493         None
494     } else {
495         Some(String::new())
496     }
497 }
498
499 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
500     debug!("nop_block_collapse {:?} {}", block_str, budget);
501     block_str.map(|block_str| {
502         if block_str.starts_with('{')
503             && budget >= 2
504             && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
505         {
506             "{}".to_owned()
507         } else {
508             block_str.to_owned()
509         }
510     })
511 }
512
513 fn can_flatten_block_around_this(body: &ast::Expr) -> bool {
514     match body.node {
515         // We do not allow `if` to stay on the same line, since we could easily mistake
516         // `pat => if cond { ... }` and `pat if cond => { ... }`.
517         ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => false,
518         // We do not allow collapsing a block around expression with condition
519         // to avoid it being cluttered with match arm.
520         ast::ExprKind::ForLoop(..) | ast::ExprKind::While(..) | ast::ExprKind::WhileLet(..) => {
521             false
522         }
523         ast::ExprKind::Loop(..)
524         | ast::ExprKind::Match(..)
525         | ast::ExprKind::Block(..)
526         | ast::ExprKind::Closure(..)
527         | ast::ExprKind::Array(..)
528         | ast::ExprKind::Call(..)
529         | ast::ExprKind::MethodCall(..)
530         | ast::ExprKind::Mac(..)
531         | ast::ExprKind::Struct(..)
532         | ast::ExprKind::Tup(..) => true,
533         ast::ExprKind::AddrOf(_, ref expr)
534         | ast::ExprKind::Box(ref expr)
535         | ast::ExprKind::Try(ref expr)
536         | ast::ExprKind::Unary(_, ref expr)
537         | ast::ExprKind::Cast(ref expr, _) => can_flatten_block_around_this(expr),
538         _ => false,
539     }
540 }