]> git.lizzy.rs Git - rust.git/blob - src/patterns.rs
Merge pull request #1964 from topecongiro/rfc/binop
[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, SeparatorPlace, 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(
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                 wrap_str(result, context.config.max_width(), shape)
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(..) => wrap_str(
134                 context.snippet(self.span),
135                 context.config.max_width(),
136                 shape,
137             ),
138         }
139     }
140 }
141
142 fn rewrite_struct_pat(
143     path: &ast::Path,
144     fields: &[codemap::Spanned<ast::FieldPat>],
145     elipses: bool,
146     span: Span,
147     context: &RewriteContext,
148     shape: Shape,
149 ) -> Option<String> {
150     // 2 =  ` {`
151     let path_shape = try_opt!(shape.sub_width(2));
152     let path_str = try_opt!(rewrite_path(
153         context,
154         PathContext::Expr,
155         None,
156         path,
157         path_shape,
158     ));
159
160     if fields.is_empty() && !elipses {
161         return Some(format!("{} {{}}", path_str));
162     }
163
164     let (elipses_str, terminator) = if elipses { (", ..", "..") } else { ("", "}") };
165
166     // 3 = ` { `, 2 = ` }`.
167     let (h_shape, v_shape) = try_opt!(struct_lit_shape(
168         shape,
169         context,
170         path_str.len() + 3,
171         elipses_str.len() + 2,
172     ));
173
174     let items = itemize_list(
175         context.codemap,
176         fields.iter(),
177         terminator,
178         |f| f.span.lo(),
179         |f| f.span.hi(),
180         |f| f.node.rewrite(context, v_shape),
181         context.codemap.span_after(span, "{"),
182         span.hi(),
183         false,
184     );
185     let item_vec = items.collect::<Vec<_>>();
186
187     let tactic = struct_lit_tactic(h_shape, context, &item_vec);
188     let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
189     let fmt = struct_lit_formatting(nested_shape, tactic, context, false);
190
191     let mut fields_str = try_opt!(write_list(&item_vec, &fmt));
192     let one_line_width = h_shape.map_or(0, |shape| shape.width);
193
194     if elipses {
195         if fields_str.contains('\n') || fields_str.len() > one_line_width {
196             // Add a missing trailing comma.
197             if fmt.trailing_separator == SeparatorTactic::Never {
198                 fields_str.push_str(",");
199             }
200             fields_str.push_str("\n");
201             fields_str.push_str(&nested_shape.indent.to_string(context.config));
202             fields_str.push_str("..");
203         } else {
204             if !fields_str.is_empty() {
205                 // there are preceeding struct fields being matched on
206                 if fmt.tactic == DefinitiveListTactic::Vertical {
207                     // if the tactic is Vertical, write_list already added a trailing ,
208                     fields_str.push_str(" ");
209                 } else {
210                     fields_str.push_str(", ");
211                 }
212             }
213             fields_str.push_str("..");
214         }
215     }
216
217     let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
218     Some(format!("{} {{{}}}", path_str, fields_str))
219 }
220
221 impl Rewrite for FieldPat {
222     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
223         let pat = self.pat.rewrite(context, shape);
224         if self.is_shorthand {
225             pat
226         } else {
227             wrap_str(
228                 format!("{}: {}", self.ident.to_string(), try_opt!(pat)),
229                 context.config.max_width(),
230                 shape,
231             )
232         }
233     }
234 }
235
236 pub enum TuplePatField<'a> {
237     Pat(&'a ptr::P<ast::Pat>),
238     Dotdot(Span),
239 }
240
241 impl<'a> Rewrite for TuplePatField<'a> {
242     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
243         match *self {
244             TuplePatField::Pat(p) => p.rewrite(context, shape),
245             TuplePatField::Dotdot(_) => Some("..".to_string()),
246         }
247     }
248 }
249
250 impl<'a> Spanned for TuplePatField<'a> {
251     fn span(&self) -> Span {
252         match *self {
253             TuplePatField::Pat(p) => p.span(),
254             TuplePatField::Dotdot(span) => span,
255         }
256     }
257 }
258
259 pub fn can_be_overflowed_pat(context: &RewriteContext, pat: &TuplePatField, len: usize) -> bool {
260     match *pat {
261         TuplePatField::Pat(pat) => match pat.node {
262             ast::PatKind::Path(..) | ast::PatKind::Tuple(..) | ast::PatKind::Struct(..) => {
263                 context.use_block_indent() && len == 1
264             }
265             ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => {
266                 can_be_overflowed_pat(context, &TuplePatField::Pat(p), len)
267             }
268             ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
269             _ => false,
270         },
271         TuplePatField::Dotdot(..) => false,
272     }
273 }
274
275 fn rewrite_tuple_pat(
276     pats: &[ptr::P<ast::Pat>],
277     dotdot_pos: Option<usize>,
278     path_str: Option<String>,
279     span: Span,
280     context: &RewriteContext,
281     shape: Shape,
282 ) -> Option<String> {
283     let mut pat_vec: Vec<_> = pats.into_iter().map(|x| TuplePatField::Pat(x)).collect();
284
285     if let Some(pos) = dotdot_pos {
286         let prev = if pos == 0 {
287             span.lo()
288         } else {
289             pats[pos - 1].span().hi()
290         };
291         let next = if pos + 1 >= pats.len() {
292             span.hi()
293         } else {
294             pats[pos + 1].span().lo()
295         };
296         let dot_span = mk_sp(prev, next);
297         let snippet = context.snippet(dot_span);
298         let lo = dot_span.lo() + BytePos(snippet.find_uncommented("..").unwrap() as u32);
299         let dotdot = TuplePatField::Dotdot(Span::new(
300             lo,
301             // 2 == "..".len()
302             lo + BytePos(2),
303             codemap::NO_EXPANSION,
304         ));
305         pat_vec.insert(pos, dotdot);
306     }
307
308     if pat_vec.is_empty() {
309         return Some(format!("{}()", path_str.unwrap_or_default()));
310     }
311
312     let wildcard_suffix_len = count_wildcard_suffix_len(context, &pat_vec, span, shape);
313     let (pat_vec, span) = if context.config.condense_wildcard_suffixes() && wildcard_suffix_len >= 2
314     {
315         let new_item_count = 1 + pat_vec.len() - wildcard_suffix_len;
316         let sp = pat_vec[new_item_count - 1].span();
317         let snippet = context.snippet(sp);
318         let lo = sp.lo() + BytePos(snippet.find_uncommented("_").unwrap() as u32);
319         pat_vec[new_item_count - 1] = TuplePatField::Dotdot(mk_sp(lo, lo + BytePos(1)));
320         (
321             &pat_vec[..new_item_count],
322             mk_sp(span.lo(), lo + BytePos(1)),
323         )
324     } else {
325         (&pat_vec[..], span)
326     };
327
328     // add comma if `(x,)`
329     let add_comma = path_str.is_none() && pat_vec.len() == 1 && dotdot_pos.is_none();
330     let mut context = context.clone();
331     if let Some(&TuplePatField::Dotdot(..)) = pat_vec.last() {
332         context.inside_macro = true;
333     }
334     let path_str = path_str.unwrap_or_default();
335     let mut pat_ref_vec = Vec::with_capacity(pat_vec.len());
336     for pat in pat_vec {
337         pat_ref_vec.push(pat);
338     }
339
340     rewrite_call_inner(
341         &context,
342         &path_str,
343         &pat_ref_vec[..],
344         span,
345         shape,
346         shape.width,
347         add_comma,
348     ).ok()
349 }
350
351 fn count_wildcard_suffix_len(
352     context: &RewriteContext,
353     patterns: &[TuplePatField],
354     span: Span,
355     shape: Shape,
356 ) -> usize {
357     let mut suffix_len = 0;
358
359     let items: Vec<_> = itemize_list(
360         context.codemap,
361         patterns.iter(),
362         ")",
363         |item| item.span().lo(),
364         |item| item.span().hi(),
365         |item| item.rewrite(context, shape),
366         context.codemap.span_after(span, "("),
367         span.hi() - BytePos(1),
368         false,
369     ).collect();
370
371     for item in items.iter().rev().take_while(|i| match i.item {
372         Some(ref internal_string) if internal_string == "_" => true,
373         _ => false,
374     }) {
375         suffix_len += 1;
376
377         if item.pre_comment.is_some() || item.post_comment.is_some() {
378             break;
379         }
380     }
381
382     suffix_len
383 }