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