]> git.lizzy.rs Git - rust.git/blob - src/patterns.rs
4285b592fbc652ce8235c3daadf54780b6ba471d
[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 Indent;
12 use rewrite::{Rewrite, RewriteContext};
13 use utils::{CodeMapSpanUtils, wrap_str, format_mutability};
14 use lists::{format_item_list, itemize_list};
15 use expr::{rewrite_unary_prefix, rewrite_pair, rewrite_tuple};
16 use types::rewrite_path;
17
18 use syntax::ast::{BindingMode, Pat, PatKind, FieldPat};
19
20 impl Rewrite for Pat {
21     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
22         match self.node {
23             PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, width, offset),
24             PatKind::Ident(binding_mode, ident, ref sub_pat) => {
25                 let (prefix, mutability) = match binding_mode {
26                     BindingMode::ByRef(mutability) => ("ref ", mutability),
27                     BindingMode::ByValue(mutability) => ("", mutability),
28                 };
29                 let mut_infix = format_mutability(mutability);
30                 let id_str = ident.node.to_string();
31
32                 let sub_pat = match *sub_pat {
33                     Some(ref p) => {
34                         // 3 - ` @ `.
35                         let width = try_opt!(width.checked_sub(prefix.len() + mut_infix.len() +
36                                                                id_str.len() +
37                                                                3));
38                         format!(" @ {}", try_opt!(p.rewrite(context, width, offset)))
39                     }
40                     None => "".to_owned(),
41                 };
42
43                 let result = format!("{}{}{}{}", prefix, mut_infix, id_str, sub_pat);
44                 wrap_str(result, context.config.max_width, width, offset)
45             }
46             PatKind::Wild => {
47                 if 1 <= width {
48                     Some("_".to_owned())
49                 } else {
50                     None
51                 }
52             }
53             PatKind::QPath(ref q_self, ref path) => {
54                 rewrite_path(context, true, Some(q_self), path, width, offset)
55             }
56             PatKind::Range(ref lhs, ref rhs) => {
57                 rewrite_pair(&**lhs, &**rhs, "", "...", "", context, width, offset)
58             }
59             PatKind::Ref(ref pat, mutability) => {
60                 let prefix = format!("&{}", format_mutability(mutability));
61                 rewrite_unary_prefix(context, &prefix, &**pat, width, offset)
62             }
63             PatKind::Tup(ref items) => {
64                 rewrite_tuple(context,
65                               items.iter().map(|x| &**x),
66                               self.span,
67                               width,
68                               offset)
69             }
70             PatKind::Path(ref path) => rewrite_path(context, true, None, path, width, offset),
71             PatKind::TupleStruct(ref path, ref pat_vec) => {
72                 let path_str = try_opt!(rewrite_path(context, true, None, path, width, offset));
73
74                 match *pat_vec {
75                     Some(ref pat_vec) => {
76                         if pat_vec.is_empty() {
77                             Some(path_str)
78                         } else {
79                             // 1 = (
80                             let width = try_opt!(width.checked_sub(path_str.len() + 1));
81                             let offset = offset + path_str.len() + 1;
82                             let items = itemize_list(context.codemap,
83                                                      pat_vec.iter(),
84                                                      ")",
85                                                      |item| item.span.lo,
86                                                      |item| item.span.hi,
87                                                      |item| item.rewrite(context, width, offset),
88                                                      context.codemap.span_after(self.span, "("),
89                                                      self.span.hi);
90                             Some(format!("{}({})",
91                                          path_str,
92                                          try_opt!(format_item_list(items,
93                                                                    width,
94                                                                    offset,
95                                                                    context.config))))
96                         }
97                     }
98                     None => Some(format!("{}(..)", path_str)),
99                 }
100             }
101             PatKind::Lit(ref expr) => expr.rewrite(context, width, offset),
102             PatKind::Vec(ref prefix, ref slice_pat, ref suffix) => {
103                 // Rewrite all the sub-patterns.
104                 let prefix = prefix.iter().map(|p| p.rewrite(context, width, offset));
105                 let slice_pat = slice_pat.as_ref().map(|p| {
106                     Some(format!("{}..", try_opt!(p.rewrite(context, width, offset))))
107                 });
108                 let suffix = suffix.iter().map(|p| p.rewrite(context, width, offset));
109
110                 // Munge them together.
111                 let pats: Option<Vec<String>> = prefix.chain(slice_pat.into_iter())
112                                                       .chain(suffix)
113                                                       .collect();
114
115                 // Check that all the rewrites succeeded, and if not return None.
116                 let pats = try_opt!(pats);
117
118                 // Unwrap all the sub-strings and join them with commas.
119                 let result = format!("[{}]", pats.join(", "));
120                 wrap_str(result, context.config.max_width, width, offset)
121             }
122             PatKind::Struct(ref path, ref fields, elipses) => {
123                 let path = try_opt!(rewrite_path(context, true, None, path, width, offset));
124
125                 let (elipses_str, terminator) = if elipses {
126                     (", ..", "..")
127                 } else {
128                     ("", "}")
129                 };
130
131                 // 5 = `{` plus space before and after plus `}` plus space before.
132                 let budget = try_opt!(width.checked_sub(path.len() + 5 + elipses_str.len()));
133                 // FIXME Using visual indenting, should use block or visual to match
134                 // struct lit preference (however, in practice I think it is rare
135                 // for struct patterns to be multi-line).
136                 // 3 = `{` plus space before and after.
137                 let offset = offset + path.len() + 3;
138
139                 let items = itemize_list(context.codemap,
140                                          fields.iter(),
141                                          terminator,
142                                          |f| f.span.lo,
143                                          |f| f.span.hi,
144                                          |f| f.node.rewrite(context, budget, offset),
145                                          context.codemap.span_after(self.span, "{"),
146                                          self.span.hi);
147                 let mut field_string = try_opt!(format_item_list(items,
148                                                                  budget,
149                                                                  offset,
150                                                                  context.config));
151                 if elipses {
152                     if field_string.contains('\n') {
153                         field_string.push_str(",\n");
154                         field_string.push_str(&offset.to_string(context.config));
155                         field_string.push_str("..");
156                     } else {
157                         if field_string.len() > 0 {
158                             field_string.push_str(", ");
159                         }
160                         field_string.push_str("..");
161                     }
162                 }
163
164                 if field_string.is_empty() {
165                     Some(format!("{} {{}}", path))
166                 } else {
167                     Some(format!("{} {{ {} }}", path, field_string))
168                 }
169             }
170             // FIXME(#819) format pattern macros.
171             PatKind::Mac(..) => {
172                 wrap_str(context.snippet(self.span),
173                          context.config.max_width,
174                          width,
175                          offset)
176             }
177         }
178     }
179 }
180
181 impl Rewrite for FieldPat {
182     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
183         let pat = self.pat.rewrite(context, width, offset);
184         if self.is_shorthand {
185             pat
186         } else {
187             wrap_str(format!("{}: {}", self.ident.to_string(), try_opt!(pat)),
188                      context.config.max_width,
189                      width,
190                      offset)
191         }
192     }
193 }