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