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