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