]> git.lizzy.rs Git - rust.git/blob - src/patterns.rs
Merge pull request #2823 from fwalch/default-newline-style
[rust.git] / src / patterns.rs
1 // Copyright 2015 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 use config::lists::*;
12 use syntax::ast::{self, BindingMode, FieldPat, Pat, PatKind, RangeEnd, RangeSyntax};
13 use syntax::codemap::{self, BytePos, Span};
14 use syntax::ptr;
15
16 use codemap::SpanUtils;
17 use comment::FindUncommented;
18 use expr::{can_be_overflowed_expr, rewrite_unary_prefix, wrap_struct_field};
19 use lists::{
20     itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape, struct_lit_tactic,
21     write_list,
22 };
23 use macros::{rewrite_macro, MacroPosition};
24 use overflow;
25 use pairs::{rewrite_pair, PairParts};
26 use rewrite::{Rewrite, RewriteContext};
27 use shape::Shape;
28 use spanned::Spanned;
29 use types::{rewrite_path, PathContext};
30 use utils::{format_mutability, mk_sp, rewrite_ident};
31
32 /// Returns true if the given pattern is short. A short pattern is defined by the following grammer:
33 ///
34 /// [small, ntp]:
35 ///     - single token
36 ///     - `&[single-line, ntp]`
37 ///
38 /// [small]:
39 ///     - `[small, ntp]`
40 ///     - unary tuple constructor `([small, ntp])`
41 ///     - `&[small]`
42 pub fn is_short_pattern(pat: &ast::Pat, pat_str: &str) -> bool {
43     // We also require that the pattern is reasonably 'small' with its literal width.
44     pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(pat)
45 }
46
47 fn is_short_pattern_inner(pat: &ast::Pat) -> bool {
48     match pat.node {
49         ast::PatKind::Wild | ast::PatKind::Lit(_) => true,
50         ast::PatKind::Ident(_, _, ref pat) => pat.is_none(),
51         ast::PatKind::Struct(..)
52         | ast::PatKind::Mac(..)
53         | ast::PatKind::Slice(..)
54         | ast::PatKind::Path(..)
55         | ast::PatKind::Range(..) => false,
56         ast::PatKind::Tuple(ref subpats, _) => subpats.len() <= 1,
57         ast::PatKind::TupleStruct(ref path, ref subpats, _) => {
58             path.segments.len() <= 1 && subpats.len() <= 1
59         }
60         ast::PatKind::Box(ref p) | ast::PatKind::Ref(ref p, _) | ast::PatKind::Paren(ref p) => {
61             is_short_pattern_inner(&*p)
62         }
63     }
64 }
65
66 impl Rewrite for Pat {
67     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
68         match self.node {
69             PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, shape),
70             PatKind::Ident(binding_mode, ident, ref sub_pat) => {
71                 let (prefix, mutability) = match binding_mode {
72                     BindingMode::ByRef(mutability) => ("ref ", mutability),
73                     BindingMode::ByValue(mutability) => ("", mutability),
74                 };
75                 let mut_infix = format_mutability(mutability);
76                 let id_str = rewrite_ident(context, ident);
77                 let sub_pat = match *sub_pat {
78                     Some(ref p) => {
79                         // 3 - ` @ `.
80                         let width = shape
81                             .width
82                             .checked_sub(prefix.len() + mut_infix.len() + id_str.len() + 3)?;
83                         format!(
84                             " @ {}",
85                             p.rewrite(context, Shape::legacy(width, shape.indent))?
86                         )
87                     }
88                     None => "".to_owned(),
89                 };
90
91                 Some(format!("{}{}{}{}", prefix, mut_infix, id_str, sub_pat))
92             }
93             PatKind::Wild => {
94                 if 1 <= shape.width {
95                     Some("_".to_owned())
96                 } else {
97                     None
98                 }
99             }
100             PatKind::Range(ref lhs, ref rhs, ref end_kind) => {
101                 let infix = match end_kind.node {
102                     RangeEnd::Included(RangeSyntax::DotDotDot) => "...",
103                     RangeEnd::Included(RangeSyntax::DotDotEq) => "..=",
104                     RangeEnd::Excluded => "..",
105                 };
106                 let infix = if context.config.spaces_around_ranges() {
107                     format!(" {} ", infix)
108                 } else {
109                     infix.to_owned()
110                 };
111                 rewrite_pair(
112                     &**lhs,
113                     &**rhs,
114                     PairParts::infix(&infix),
115                     context,
116                     shape,
117                     SeparatorPlace::Front,
118                 )
119             }
120             PatKind::Ref(ref pat, mutability) => {
121                 let prefix = format!("&{}", format_mutability(mutability));
122                 rewrite_unary_prefix(context, &prefix, &**pat, shape)
123             }
124             PatKind::Tuple(ref items, dotdot_pos) => {
125                 rewrite_tuple_pat(items, dotdot_pos, None, self.span, context, shape)
126             }
127             PatKind::Path(ref q_self, ref path) => {
128                 rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)
129             }
130             PatKind::TupleStruct(ref path, ref pat_vec, dotdot_pos) => {
131                 let path_str = rewrite_path(context, PathContext::Expr, None, path, shape)?;
132                 rewrite_tuple_pat(
133                     pat_vec,
134                     dotdot_pos,
135                     Some(path_str),
136                     self.span,
137                     context,
138                     shape,
139                 )
140             }
141             PatKind::Lit(ref expr) => expr.rewrite(context, shape),
142             PatKind::Slice(ref prefix, ref slice_pat, ref suffix) => {
143                 // Rewrite all the sub-patterns.
144                 let prefix = prefix.iter().map(|p| p.rewrite(context, shape));
145                 let slice_pat = slice_pat
146                     .as_ref()
147                     .map(|p| Some(format!("{}..", p.rewrite(context, shape)?)));
148                 let suffix = suffix.iter().map(|p| p.rewrite(context, shape));
149
150                 // Munge them together.
151                 let pats: Option<Vec<String>> =
152                     prefix.chain(slice_pat.into_iter()).chain(suffix).collect();
153
154                 // Check that all the rewrites succeeded, and if not return None.
155                 let pats = pats?;
156
157                 // Unwrap all the sub-strings and join them with commas.
158                 Some(format!("[{}]", pats.join(", ")))
159             }
160             PatKind::Struct(ref path, ref fields, ellipsis) => {
161                 rewrite_struct_pat(path, fields, ellipsis, self.span, context, shape)
162             }
163             PatKind::Mac(ref mac) => rewrite_macro(mac, None, context, shape, MacroPosition::Pat),
164             PatKind::Paren(ref pat) => pat
165                 .rewrite(context, shape.offset_left(1)?.sub_width(1)?)
166                 .map(|inner_pat| format!("({})", inner_pat)),
167         }
168     }
169 }
170
171 fn rewrite_struct_pat(
172     path: &ast::Path,
173     fields: &[codemap::Spanned<ast::FieldPat>],
174     ellipsis: bool,
175     span: Span,
176     context: &RewriteContext,
177     shape: Shape,
178 ) -> Option<String> {
179     // 2 =  ` {`
180     let path_shape = shape.sub_width(2)?;
181     let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
182
183     if fields.is_empty() && !ellipsis {
184         return Some(format!("{} {{}}", path_str));
185     }
186
187     let (ellipsis_str, terminator) = if ellipsis { (", ..", "..") } else { ("", "}") };
188
189     // 3 = ` { `, 2 = ` }`.
190     let (h_shape, v_shape) =
191         struct_lit_shape(shape, context, path_str.len() + 3, ellipsis_str.len() + 2)?;
192
193     let items = itemize_list(
194         context.snippet_provider,
195         fields.iter(),
196         terminator,
197         ",",
198         |f| f.span.lo(),
199         |f| f.span.hi(),
200         |f| f.node.rewrite(context, v_shape),
201         context.snippet_provider.span_after(span, "{"),
202         span.hi(),
203         false,
204     );
205     let item_vec = items.collect::<Vec<_>>();
206
207     let tactic = struct_lit_tactic(h_shape, context, &item_vec);
208     let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
209     let fmt = struct_lit_formatting(nested_shape, tactic, context, false);
210
211     let mut fields_str = write_list(&item_vec, &fmt)?;
212     let one_line_width = h_shape.map_or(0, |shape| shape.width);
213
214     if ellipsis {
215         if fields_str.contains('\n') || fields_str.len() > one_line_width {
216             // Add a missing trailing comma.
217             if fmt.trailing_separator == SeparatorTactic::Never {
218                 fields_str.push_str(",");
219             }
220             fields_str.push_str("\n");
221             fields_str.push_str(&nested_shape.indent.to_string(context.config));
222             fields_str.push_str("..");
223         } else {
224             if !fields_str.is_empty() {
225                 // there are preceding struct fields being matched on
226                 if fmt.tactic == DefinitiveListTactic::Vertical {
227                     // if the tactic is Vertical, write_list already added a trailing ,
228                     fields_str.push_str(" ");
229                 } else {
230                     fields_str.push_str(", ");
231                 }
232             }
233             fields_str.push_str("..");
234         }
235     }
236
237     let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
238     Some(format!("{} {{{}}}", path_str, fields_str))
239 }
240
241 impl Rewrite for FieldPat {
242     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
243         let pat = self.pat.rewrite(context, shape);
244         if self.is_shorthand {
245             pat
246         } else {
247             let pat_str = pat?;
248             let id_str = rewrite_ident(context, self.ident);
249             let one_line_width = id_str.len() + 2 + pat_str.len();
250             if one_line_width <= shape.width {
251                 Some(format!("{}: {}", id_str, pat_str))
252             } else {
253                 let nested_shape = shape.block_indent(context.config.tab_spaces());
254                 let pat_str = self.pat.rewrite(context, nested_shape)?;
255                 Some(format!(
256                     "{}:\n{}{}",
257                     id_str,
258                     nested_shape.indent.to_string(context.config),
259                     pat_str,
260                 ))
261             }
262         }
263     }
264 }
265
266 pub enum TuplePatField<'a> {
267     Pat(&'a ptr::P<ast::Pat>),
268     Dotdot(Span),
269 }
270
271 impl<'a> Rewrite for TuplePatField<'a> {
272     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
273         match *self {
274             TuplePatField::Pat(p) => p.rewrite(context, shape),
275             TuplePatField::Dotdot(_) => Some("..".to_string()),
276         }
277     }
278 }
279
280 impl<'a> Spanned for TuplePatField<'a> {
281     fn span(&self) -> Span {
282         match *self {
283             TuplePatField::Pat(p) => p.span(),
284             TuplePatField::Dotdot(span) => span,
285         }
286     }
287 }
288
289 pub fn can_be_overflowed_pat(context: &RewriteContext, pat: &TuplePatField, len: usize) -> bool {
290     match *pat {
291         TuplePatField::Pat(pat) => match pat.node {
292             ast::PatKind::Path(..)
293             | ast::PatKind::Tuple(..)
294             | ast::PatKind::Struct(..)
295             | ast::PatKind::TupleStruct(..) => context.use_block_indent() && len == 1,
296             ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => {
297                 can_be_overflowed_pat(context, &TuplePatField::Pat(p), len)
298             }
299             ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
300             _ => false,
301         },
302         TuplePatField::Dotdot(..) => false,
303     }
304 }
305
306 fn rewrite_tuple_pat(
307     pats: &[ptr::P<ast::Pat>],
308     dotdot_pos: Option<usize>,
309     path_str: Option<String>,
310     span: Span,
311     context: &RewriteContext,
312     shape: Shape,
313 ) -> Option<String> {
314     let mut pat_vec: Vec<_> = pats.into_iter().map(|x| TuplePatField::Pat(x)).collect();
315
316     if let Some(pos) = dotdot_pos {
317         let prev = if pos == 0 {
318             span.lo()
319         } else {
320             pats[pos - 1].span().hi()
321         };
322         let next = if pos + 1 >= pats.len() {
323             span.hi()
324         } else {
325             pats[pos + 1].span().lo()
326         };
327         let dot_span = mk_sp(prev, next);
328         let snippet = context.snippet(dot_span);
329         let lo = dot_span.lo() + BytePos(snippet.find_uncommented("..").unwrap() as u32);
330         let dotdot = TuplePatField::Dotdot(Span::new(
331             lo,
332             // 2 == "..".len()
333             lo + BytePos(2),
334             codemap::NO_EXPANSION,
335         ));
336         pat_vec.insert(pos, dotdot);
337     }
338
339     if pat_vec.is_empty() {
340         return Some(format!("{}()", path_str.unwrap_or_default()));
341     }
342
343     let wildcard_suffix_len = count_wildcard_suffix_len(context, &pat_vec, span, shape);
344     let (pat_vec, span) = if context.config.condense_wildcard_suffixes() && wildcard_suffix_len >= 2
345     {
346         let new_item_count = 1 + pat_vec.len() - wildcard_suffix_len;
347         let sp = pat_vec[new_item_count - 1].span();
348         let snippet = context.snippet(sp);
349         let lo = sp.lo() + BytePos(snippet.find_uncommented("_").unwrap() as u32);
350         pat_vec[new_item_count - 1] = TuplePatField::Dotdot(mk_sp(lo, lo + BytePos(1)));
351         (
352             &pat_vec[..new_item_count],
353             mk_sp(span.lo(), lo + BytePos(1)),
354         )
355     } else {
356         (&pat_vec[..], span)
357     };
358
359     // add comma if `(x,)`
360     let add_comma = path_str.is_none() && pat_vec.len() == 1 && dotdot_pos.is_none();
361     let path_str = path_str.unwrap_or_default();
362     let pat_ref_vec = pat_vec.iter().collect::<Vec<_>>();
363
364     overflow::rewrite_with_parens(
365         &context,
366         &path_str,
367         &pat_ref_vec,
368         shape,
369         span,
370         context.config.max_width(),
371         if add_comma {
372             Some(SeparatorTactic::Always)
373         } else {
374             None
375         },
376     )
377 }
378
379 fn count_wildcard_suffix_len(
380     context: &RewriteContext,
381     patterns: &[TuplePatField],
382     span: Span,
383     shape: Shape,
384 ) -> usize {
385     let mut suffix_len = 0;
386
387     let items: Vec<_> = itemize_list(
388         context.snippet_provider,
389         patterns.iter(),
390         ")",
391         ",",
392         |item| item.span().lo(),
393         |item| item.span().hi(),
394         |item| item.rewrite(context, shape),
395         context.snippet_provider.span_after(span, "("),
396         span.hi() - BytePos(1),
397         false,
398     ).collect();
399
400     for item in items.iter().rev().take_while(|i| match i.item {
401         Some(ref internal_string) if internal_string == "_" => true,
402         _ => false,
403     }) {
404         suffix_len += 1;
405
406         if item.has_comment() {
407             break;
408         }
409     }
410
411     suffix_len
412 }