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