]> git.lizzy.rs Git - rust.git/blob - src/matches.rs
Add matches module
[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::{ast, ptr};
17 use syntax::codemap::{BytePos, Span};
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         Some(format!(
137             "match {}{}{{\n{}{}{}\n{}}}",
138             cond_str,
139             block_sep,
140             inner_attrs_str,
141             nested_indent_str,
142             rewrite_match_arms(context, arms, shape, span, open_brace_pos)?,
143             shape.indent.to_string(context.config),
144         ))
145     }
146 }
147
148 fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
149     if is_last && config.trailing_comma() == SeparatorTactic::Never {
150         ""
151     } else if config.match_block_trailing_comma() {
152         ","
153     } else if let ast::ExprKind::Block(ref block) = body.node {
154         if let ast::BlockCheckMode::Default = block.rules {
155             ""
156         } else {
157             ","
158         }
159     } else {
160         ","
161     }
162 }
163
164 /// Collect a byte position of the beginning `|` for each arm, if available.
165 fn collect_beginning_verts(
166     context: &RewriteContext,
167     arms: &[ast::Arm],
168     span: Span,
169 ) -> Vec<Option<BytePos>> {
170     let mut beginning_verts = Vec::with_capacity(arms.len());
171     let mut lo = context.snippet_provider.span_after(span, "{");
172     for arm in arms {
173         let hi = arm.pats[0].span.lo();
174         let missing_span = mk_sp(lo, hi);
175         beginning_verts.push(context.snippet_provider.opt_span_before(missing_span, "|"));
176         lo = arm.span().hi();
177     }
178     beginning_verts
179 }
180
181 fn rewrite_match_arms(
182     context: &RewriteContext,
183     arms: &[ast::Arm],
184     shape: Shape,
185     span: Span,
186     open_brace_pos: BytePos,
187 ) -> Option<String> {
188     let arm_shape = shape
189         .block_indent(context.config.tab_spaces())
190         .with_max_width(context.config);
191
192     let arm_len = arms.len();
193     let is_last_iter = repeat(false)
194         .take(arm_len.checked_sub(1).unwrap_or(0))
195         .chain(repeat(true));
196     let beginning_verts = collect_beginning_verts(context, arms, span);
197     let items = itemize_list(
198         context.snippet_provider,
199         arms.iter()
200             .zip(is_last_iter)
201             .zip(beginning_verts.into_iter())
202             .map(|((arm, is_last), beginning_vert)| ArmWrapper::new(arm, is_last, beginning_vert)),
203         "}",
204         "|",
205         |arm| arm.span().lo(),
206         |arm| arm.span().hi(),
207         |arm| arm.rewrite(context, arm_shape),
208         open_brace_pos,
209         span.hi(),
210         false,
211     );
212     let arms_vec: Vec<_> = items.collect();
213     let fmt = ListFormatting {
214         tactic: DefinitiveListTactic::Vertical,
215         // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
216         separator: "",
217         trailing_separator: SeparatorTactic::Never,
218         separator_place: SeparatorPlace::Back,
219         shape: arm_shape,
220         ends_with_newline: true,
221         preserve_newline: true,
222         config: context.config,
223     };
224
225     write_list(&arms_vec, &fmt)
226 }
227
228 fn rewrite_match_arm(
229     context: &RewriteContext,
230     arm: &ast::Arm,
231     shape: Shape,
232     is_last: bool,
233     beginning_vert: Option<BytePos>,
234 ) -> Option<String> {
235     let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
236         if contains_skip(&arm.attrs) {
237             let (_, body) = flatten_arm_body(context, &arm.body);
238             // `arm.span()` does not include trailing comma, add it manually.
239             return Some(format!(
240                 "{}{}",
241                 context.snippet(arm.span()),
242                 arm_comma(context.config, body, is_last),
243             ));
244         }
245         let missing_span = mk_sp(
246             arm.attrs[arm.attrs.len() - 1].span.hi(),
247             arm.pats[0].span.lo(),
248         );
249         (missing_span, arm.attrs.rewrite(context, shape)?)
250     } else {
251         (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
252     };
253     let pats_str = rewrite_match_pattern(
254         context,
255         &ptr_vec_to_ref_vec(&arm.pats),
256         &arm.guard,
257         beginning_vert.is_some(),
258         shape,
259     ).and_then(|pats_str| {
260         combine_strs_with_missing_comments(
261             context,
262             &attrs_str,
263             &pats_str,
264             missing_span,
265             shape,
266             false,
267         )
268     })?;
269     rewrite_match_body(
270         context,
271         &arm.body,
272         &pats_str,
273         shape,
274         arm.guard.is_some(),
275         is_last,
276     )
277 }
278
279 fn rewrite_match_pattern(
280     context: &RewriteContext,
281     pats: &[&ast::Pat],
282     guard: &Option<ptr::P<ast::Expr>>,
283     has_beginning_vert: bool,
284     shape: Shape,
285 ) -> Option<String> {
286     // Patterns
287     // 5 = ` => {`
288     // 2 = `| `
289     let pat_shape = shape
290         .sub_width(5)?
291         .offset_left(if has_beginning_vert { 2 } else { 0 })?;
292     let pats_str = rewrite_multiple_patterns(context, pats, pat_shape)?;
293     let beginning_vert = if has_beginning_vert { "| " } else { "" };
294
295     // Guard
296     let guard_str = rewrite_guard(context, guard, shape, trimmed_last_line_width(&pats_str))?;
297
298     Some(format!("{}{}{}", beginning_vert, pats_str, guard_str))
299 }
300
301 // (extend, body)
302 // @extend: true if the arm body can be put next to `=>`
303 // @body: flattened body, if the body is block with a single expression
304 fn flatten_arm_body<'a>(context: &'a RewriteContext, body: &'a ast::Expr) -> (bool, &'a ast::Expr) {
305     match body.node {
306         ast::ExprKind::Block(ref block)
307             if !is_unsafe_block(block)
308                 && is_simple_block(block, Some(&body.attrs), context.codemap) =>
309         {
310             if let ast::StmtKind::Expr(ref expr) = block.stmts[0].node {
311                 (
312                     !context.config.force_multiline_blocks() && can_extend_match_arm_body(expr),
313                     &*expr,
314                 )
315             } else {
316                 (false, &*body)
317             }
318         }
319         _ => (
320             !context.config.force_multiline_blocks() && body.can_be_overflowed(context, 1),
321             &*body,
322         ),
323     }
324 }
325
326 fn rewrite_match_body(
327     context: &RewriteContext,
328     body: &ptr::P<ast::Expr>,
329     pats_str: &str,
330     shape: Shape,
331     has_guard: bool,
332     is_last: bool,
333 ) -> Option<String> {
334     let (extend, body) = flatten_arm_body(context, body);
335     let (is_block, is_empty_block) = if let ast::ExprKind::Block(ref block) = body.node {
336         (
337             true,
338             is_empty_block(block, Some(&body.attrs), context.codemap),
339         )
340     } else {
341         (false, false)
342     };
343
344     let comma = arm_comma(context.config, body, is_last);
345     let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
346
347     let combine_orig_body = |body_str: &str| {
348         let block_sep = match context.config.control_brace_style() {
349             ControlBraceStyle::AlwaysNextLine if is_block => alt_block_sep,
350             _ => " ",
351         };
352
353         Some(format!("{} =>{}{}{}", pats_str, block_sep, body_str, comma))
354     };
355
356     let forbid_same_line = has_guard && pats_str.contains('\n') && !is_empty_block;
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     let combine_next_line_body = |body_str: &str| {
363         if is_block {
364             return Some(format!(
365                 "{} =>{}{}",
366                 pats_str,
367                 next_line_indent.to_string_with_newline(context.config),
368                 body_str
369             ));
370         }
371
372         let indent_str = shape.indent.to_string_with_newline(context.config);
373         let nested_indent_str = next_line_indent.to_string_with_newline(context.config);
374         let (body_prefix, body_suffix) = if context.config.match_arm_blocks() {
375             let comma = if context.config.match_block_trailing_comma() {
376                 ","
377             } else {
378                 ""
379             };
380             ("{", format!("{}}}{}", indent_str, comma))
381         } else {
382             ("", String::from(","))
383         };
384
385         let block_sep = match context.config.control_brace_style() {
386             ControlBraceStyle::AlwaysNextLine => format!("{}{}", alt_block_sep, body_prefix),
387             _ if body_prefix.is_empty() => "".to_owned(),
388             _ if forbid_same_line => format!("{}{}", alt_block_sep, body_prefix),
389             _ => format!(" {}", body_prefix),
390         } + &nested_indent_str;
391
392         Some(format!(
393             "{} =>{}{}{}",
394             pats_str, block_sep, body_str, body_suffix
395         ))
396     };
397
398     // Let's try and get the arm body on the same line as the condition.
399     // 4 = ` => `.len()
400     let orig_body_shape = shape
401         .offset_left(extra_offset(pats_str, shape) + 4)
402         .and_then(|shape| shape.sub_width(comma.len()));
403     let orig_body = if let Some(body_shape) = orig_body_shape {
404         let rewrite = nop_block_collapse(
405             format_expr(body, ExprType::Statement, context, body_shape),
406             body_shape.width,
407         );
408
409         match rewrite {
410             Some(ref body_str)
411                 if !forbid_same_line
412                     && (is_block
413                         || (!body_str.contains('\n') && body_str.len() <= body_shape.width)) =>
414             {
415                 return combine_orig_body(body_str);
416             }
417             _ => rewrite,
418         }
419     } else {
420         None
421     };
422     let orig_budget = orig_body_shape.map_or(0, |shape| shape.width);
423
424     // Try putting body on the next line and see if it looks better.
425     let next_line_body_shape = Shape::indented(next_line_indent, context.config);
426     let next_line_body = nop_block_collapse(
427         format_expr(body, ExprType::Statement, context, next_line_body_shape),
428         next_line_body_shape.width,
429     );
430     match (orig_body, next_line_body) {
431         (Some(ref orig_str), Some(ref next_line_str))
432             if forbid_same_line
433                 || prefer_next_line(orig_str, next_line_str, RhsTactics::Default) =>
434         {
435             combine_next_line_body(next_line_str)
436         }
437         (Some(ref orig_str), _) if extend && first_line_width(orig_str) <= orig_budget => {
438             combine_orig_body(orig_str)
439         }
440         (Some(ref orig_str), Some(ref next_line_str)) if orig_str.contains('\n') => {
441             combine_next_line_body(next_line_str)
442         }
443         (None, Some(ref next_line_str)) => combine_next_line_body(next_line_str),
444         (None, None) => None,
445         (Some(ref orig_str), _) => combine_orig_body(orig_str),
446     }
447 }
448
449 // The `if ...` guard on a match arm.
450 fn rewrite_guard(
451     context: &RewriteContext,
452     guard: &Option<ptr::P<ast::Expr>>,
453     shape: Shape,
454     // The amount of space used up on this line for the pattern in
455     // the arm (excludes offset).
456     pattern_width: usize,
457 ) -> Option<String> {
458     if let Some(ref guard) = *guard {
459         // First try to fit the guard string on the same line as the pattern.
460         // 4 = ` if `, 5 = ` => {`
461         let cond_shape = shape
462             .offset_left(pattern_width + 4)
463             .and_then(|s| s.sub_width(5));
464         if let Some(cond_shape) = cond_shape {
465             if let Some(cond_str) = guard.rewrite(context, cond_shape) {
466                 if !cond_str.contains('\n') || pattern_width <= context.config.tab_spaces() {
467                     return Some(format!(" if {}", cond_str));
468                 }
469             }
470         }
471
472         // Not enough space to put the guard after the pattern, try a newline.
473         // 3 = `if `, 5 = ` => {`
474         let cond_shape = Shape::indented(shape.indent.block_indent(context.config), context.config)
475             .offset_left(3)
476             .and_then(|s| s.sub_width(5));
477         if let Some(cond_shape) = cond_shape {
478             if let Some(cond_str) = guard.rewrite(context, cond_shape) {
479                 return Some(format!(
480                     "{}if {}",
481                     cond_shape.indent.to_string_with_newline(context.config),
482                     cond_str
483                 ));
484             }
485         }
486
487         None
488     } else {
489         Some(String::new())
490     }
491 }
492
493 fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
494     debug!("nop_block_collapse {:?} {}", block_str, budget);
495     block_str.map(|block_str| {
496         if block_str.starts_with('{') && budget >= 2
497             && (block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
498         {
499             "{}".to_owned()
500         } else {
501             block_str.to_owned()
502         }
503     })
504 }
505
506 fn can_extend_match_arm_body(body: &ast::Expr) -> bool {
507     match body.node {
508         // We do not allow `if` to stay on the same line, since we could easily mistake
509         // `pat => if cond { ... }` and `pat if cond => { ... }`.
510         ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => false,
511         ast::ExprKind::ForLoop(..)
512         | ast::ExprKind::Loop(..)
513         | ast::ExprKind::While(..)
514         | ast::ExprKind::WhileLet(..)
515         | ast::ExprKind::Match(..)
516         | ast::ExprKind::Block(..)
517         | ast::ExprKind::Closure(..)
518         | ast::ExprKind::Array(..)
519         | ast::ExprKind::Call(..)
520         | ast::ExprKind::MethodCall(..)
521         | ast::ExprKind::Mac(..)
522         | ast::ExprKind::Struct(..)
523         | ast::ExprKind::Tup(..) => true,
524         ast::ExprKind::AddrOf(_, ref expr)
525         | ast::ExprKind::Box(ref expr)
526         | ast::ExprKind::Try(ref expr)
527         | ast::ExprKind::Unary(_, ref expr)
528         | ast::ExprKind::Cast(ref expr, _) => can_extend_match_arm_body(expr),
529         _ => false,
530     }
531 }