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