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