]> git.lizzy.rs Git - rust.git/blob - src/patterns.rs
Merge pull request #1568 from mathstuf/suffixes-typo
[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 Shape;
12 use codemap::SpanUtils;
13 use config::{IndentStyle, MultilineStyle};
14 use rewrite::{Rewrite, RewriteContext};
15 use utils::{wrap_str, format_mutability};
16 use lists::{DefinitiveListTactic, SeparatorTactic, format_item_list, itemize_list, ListItem,
17             struct_lit_shape, struct_lit_tactic, shape_for_tactic, struct_lit_formatting,
18             write_list};
19 use expr::{rewrite_unary_prefix, rewrite_pair};
20 use types::{rewrite_path, PathContext};
21 use super::Spanned;
22 use comment::FindUncommented;
23
24 use syntax::ast::{self, BindingMode, Pat, PatKind, FieldPat, RangeEnd};
25 use syntax::ptr;
26 use syntax::codemap::{self, BytePos, Span};
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 = try_opt!(shape.width.checked_sub(prefix.len() +
43                                                                      mut_infix.len() +
44                                                                      id_str.len() +
45                                                                      3));
46                         format!(" @ {}",
47                                 try_opt!(p.rewrite(context, Shape::legacy(width, shape.indent))))
48                     }
49                     None => "".to_owned(),
50                 };
51
52                 let result = format!("{}{}{}{}", prefix, mut_infix, id_str, sub_pat);
53                 wrap_str(result, context.config.max_width, shape)
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                 match *end_kind {
64                     RangeEnd::Included => {
65                         rewrite_pair(&**lhs, &**rhs, "", "...", "", context, shape)
66                     }
67                     RangeEnd::Excluded => {
68                         rewrite_pair(&**lhs, &**rhs, "", "..", "", context, shape)
69                     }
70                 }
71             }
72             PatKind::Ref(ref pat, mutability) => {
73                 let prefix = format!("&{}", format_mutability(mutability));
74                 rewrite_unary_prefix(context, &prefix, &**pat, shape)
75             }
76             PatKind::Tuple(ref items, dotdot_pos) => {
77                 rewrite_tuple_pat(items, dotdot_pos, None, self.span, context, shape)
78             }
79             PatKind::Path(ref q_self, ref path) => {
80                 rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)
81             }
82             PatKind::TupleStruct(ref path, ref pat_vec, dotdot_pos) => {
83                 let path_str =
84                     try_opt!(rewrite_path(context, PathContext::Expr, None, path, shape));
85                 rewrite_tuple_pat(pat_vec,
86                                   dotdot_pos,
87                                   Some(path_str),
88                                   self.span,
89                                   context,
90                                   shape)
91             }
92             PatKind::Lit(ref expr) => expr.rewrite(context, shape),
93             PatKind::Slice(ref prefix, ref slice_pat, ref suffix) => {
94                 // Rewrite all the sub-patterns.
95                 let prefix = prefix.iter().map(|p| p.rewrite(context, shape));
96                 let slice_pat =
97                     slice_pat
98                         .as_ref()
99                         .map(|p| Some(format!("{}..", try_opt!(p.rewrite(context, shape)))));
100                 let suffix = suffix.iter().map(|p| p.rewrite(context, shape));
101
102                 // Munge them together.
103                 let pats: Option<Vec<String>> =
104                     prefix.chain(slice_pat.into_iter()).chain(suffix).collect();
105
106                 // Check that all the rewrites succeeded, and if not return None.
107                 let pats = try_opt!(pats);
108
109                 // Unwrap all the sub-strings and join them with commas.
110                 let result = if context.config.spaces_within_square_brackets {
111                     format!("[ {} ]", pats.join(", "))
112                 } else {
113                     format!("[{}]", pats.join(", "))
114                 };
115                 wrap_str(result, context.config.max_width, shape)
116             }
117             PatKind::Struct(ref path, ref fields, elipses) => {
118                 rewrite_struct_pat(path, fields, elipses, self.span, context, shape)
119             }
120             // FIXME(#819) format pattern macros.
121             PatKind::Mac(..) => {
122                 wrap_str(context.snippet(self.span), context.config.max_width, shape)
123             }
124         }
125     }
126 }
127
128 fn rewrite_struct_pat(path: &ast::Path,
129                       fields: &[codemap::Spanned<ast::FieldPat>],
130                       elipses: bool,
131                       span: Span,
132                       context: &RewriteContext,
133                       shape: Shape)
134                       -> Option<String> {
135     // 2 =  ` {`
136     let path_shape = try_opt!(shape.sub_width(2));
137     let path_str = try_opt!(rewrite_path(context, PathContext::Expr, None, path, path_shape));
138
139     if fields.len() == 0 && !elipses {
140         return Some(format!("{} {{}}", path_str));
141     }
142
143     let (elipses_str, terminator) = if elipses { (", ..", "..") } else { ("", "}") };
144
145     // 3 = ` { `, 2 = ` }`.
146     let (h_shape, v_shape) =
147         try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, elipses_str.len() + 2));
148
149     let items = itemize_list(context.codemap,
150                              fields.iter(),
151                              terminator,
152                              |f| f.span.lo,
153                              |f| f.span.hi,
154                              |f| f.node.rewrite(context, v_shape),
155                              context.codemap.span_after(span, "{"),
156                              span.hi);
157     let item_vec = items.collect::<Vec<_>>();
158
159     let tactic = struct_lit_tactic(h_shape, context, &item_vec);
160     let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
161     let fmt = struct_lit_formatting(nested_shape, tactic, context, false);
162
163     let mut fields_str = try_opt!(write_list(&item_vec, &fmt));
164
165     if elipses {
166         if fields_str.contains('\n') {
167             // Add a missing trailing comma.
168             if fmt.trailing_separator == SeparatorTactic::Never {
169                 fields_str.push_str(",");
170             }
171             fields_str.push_str("\n");
172             fields_str.push_str(&nested_shape.indent.to_string(context.config));
173             fields_str.push_str("..");
174         } else {
175             if !fields_str.is_empty() {
176                 // there are preceeding struct fields being matched on
177                 if fmt.tactic == DefinitiveListTactic::Vertical {
178                     // if the tactic is Vertical, write_list already added a trailing ,
179                     fields_str.push_str(" ");
180                 } else {
181                     fields_str.push_str(", ");
182                 }
183             }
184             fields_str.push_str("..");
185         }
186     }
187
188
189     let fields_str = if context.config.struct_lit_style == IndentStyle::Block &&
190                         (fields_str.contains('\n') ||
191                          context.config.struct_lit_multiline_style == MultilineStyle::ForceMulti ||
192                          fields_str.len() > h_shape.map(|s| s.width).unwrap_or(0)) {
193         format!("\n{}{}\n{}",
194                 v_shape.indent.to_string(context.config),
195                 fields_str,
196                 shape.indent.to_string(context.config))
197     } else {
198         // One liner or visual indent.
199         format!(" {} ", fields_str)
200     };
201
202     Some(format!("{} {{{}}}", path_str, fields_str))
203 }
204
205 impl Rewrite for FieldPat {
206     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
207         let pat = self.pat.rewrite(context, shape);
208         if self.is_shorthand {
209             pat
210         } else {
211             wrap_str(format!("{}: {}", self.ident.to_string(), try_opt!(pat)),
212                      context.config.max_width,
213                      shape)
214         }
215     }
216 }
217
218 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(ref 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(ref p) => p.span(),
236             TuplePatField::Dotdot(span) => span,
237         }
238     }
239 }
240
241 fn rewrite_tuple_pat(pats: &[ptr::P<ast::Pat>],
242                      dotdot_pos: Option<usize>,
243                      path_str: Option<String>,
244                      span: Span,
245                      context: &RewriteContext,
246                      shape: Shape)
247                      -> Option<String> {
248     let mut pat_vec: Vec<_> = pats.into_iter().map(|x| TuplePatField::Pat(x)).collect();
249
250     if let Some(pos) = dotdot_pos {
251         let prev = if pos == 0 {
252             span.lo
253         } else {
254             pats[pos - 1].span().hi
255         };
256         let next = if pos + 1 >= pats.len() {
257             span.hi
258         } else {
259             pats[pos + 1].span().lo
260         };
261         let dot_span = codemap::mk_sp(prev, next);
262         let snippet = context.snippet(dot_span);
263         let lo = dot_span.lo + BytePos(snippet.find_uncommented("..").unwrap() as u32);
264         let span = Span {
265             lo: lo,
266             // 2 == "..".len()
267             hi: lo + BytePos(2),
268             expn_id: codemap::NO_EXPANSION,
269         };
270         let dotdot = TuplePatField::Dotdot(span);
271         pat_vec.insert(pos, dotdot);
272     }
273
274     if pat_vec.is_empty() {
275         return Some(format!("{}()", try_opt!(path_str)));
276     }
277     // add comma if `(x,)`
278     let add_comma = path_str.is_none() && pat_vec.len() == 1 && dotdot_pos.is_none();
279
280     let path_len = path_str.as_ref().map(|p| p.len()).unwrap_or(0);
281     // 2 = "()".len(), 3 = "(,)".len()
282     let nested_shape = try_opt!(shape.sub_width(path_len + if add_comma { 3 } else { 2 }));
283     // 1 = "(".len()
284     let nested_shape = nested_shape.visual_indent(path_len + 1);
285     let mut items: Vec<_> = itemize_list(context.codemap,
286                                          pat_vec.iter(),
287                                          if add_comma { ",)" } else { ")" },
288                                          |item| item.span().lo,
289                                          |item| item.span().hi,
290                                          |item| item.rewrite(context, nested_shape),
291                                          context.codemap.span_after(span, "("),
292                                          span.hi - BytePos(1))
293             .collect();
294
295     // Condense wildcard string suffix into a single ..
296     let wildcard_suffix_len = count_wildcard_suffix_len(&items);
297
298     let list = if context.config.condense_wildcard_suffixes && wildcard_suffix_len >= 2 {
299         let new_item_count = 1 + pats.len() - wildcard_suffix_len;
300         items[new_item_count - 1].item = Some("..".to_owned());
301
302         let da_iter = items.into_iter().take(new_item_count);
303         try_opt!(format_item_list(da_iter, nested_shape, context.config))
304     } else {
305         try_opt!(format_item_list(items.into_iter(), nested_shape, context.config))
306     };
307
308     match path_str {
309         Some(path_str) => {
310             Some(if context.config.spaces_within_parens {
311                      format!("{}( {} )", path_str, list)
312                  } else {
313                      format!("{}({})", path_str, list)
314                  })
315         }
316         None => {
317             let comma = if add_comma { "," } else { "" };
318             Some(if context.config.spaces_within_parens {
319                      format!("( {}{} )", list, comma)
320                  } else {
321                      format!("({}{})", list, comma)
322                  })
323         }
324     }
325 }
326
327 fn count_wildcard_suffix_len(items: &[ListItem]) -> usize {
328     let mut suffix_len = 0;
329
330     for item in items.iter().rev().take_while(|i| match i.item {
331                                                   Some(ref internal_string) if internal_string ==
332                                                                                "_" => true,
333                                                   _ => false,
334                                               }) {
335         suffix_len += 1;
336
337         if item.pre_comment.is_some() || item.post_comment.is_some() {
338             break;
339         }
340     }
341
342     suffix_len
343 }