]> git.lizzy.rs Git - rust.git/blob - src/patterns.rs
Fix off-by-one error in pattern formatting
[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                             // 2 = "()".len()
80                             let width = try_opt!(width.checked_sub(path_str.len() + 2));
81                             // 1 = "(".len()
82                             let offset = offset + path_str.len() + 1;
83                             let items = itemize_list(context.codemap,
84                                                      pat_vec.iter(),
85                                                      ")",
86                                                      |item| item.span.lo,
87                                                      |item| item.span.hi,
88                                                      |item| item.rewrite(context, width, offset),
89                                                      context.codemap.span_after(self.span, "("),
90                                                      self.span.hi);
91                             Some(format!("{}({})",
92                                          path_str,
93                                          try_opt!(format_item_list(items,
94                                                                    width,
95                                                                    offset,
96                                                                    context.config))))
97                         }
98                     }
99                     None => Some(format!("{}(..)", path_str)),
100                 }
101             }
102             PatKind::Lit(ref expr) => expr.rewrite(context, width, offset),
103             PatKind::Vec(ref prefix, ref slice_pat, ref suffix) => {
104                 // Rewrite all the sub-patterns.
105                 let prefix = prefix.iter().map(|p| p.rewrite(context, width, offset));
106                 let slice_pat = slice_pat.as_ref().map(|p| {
107                     Some(format!("{}..", try_opt!(p.rewrite(context, width, offset))))
108                 });
109                 let suffix = suffix.iter().map(|p| p.rewrite(context, width, offset));
110
111                 // Munge them together.
112                 let pats: Option<Vec<String>> = prefix.chain(slice_pat.into_iter())
113                                                       .chain(suffix)
114                                                       .collect();
115
116                 // Check that all the rewrites succeeded, and if not return None.
117                 let pats = try_opt!(pats);
118
119                 // Unwrap all the sub-strings and join them with commas.
120                 let result = format!("[{}]", pats.join(", "));
121                 wrap_str(result, context.config.max_width, width, offset)
122             }
123             PatKind::Struct(ref path, ref fields, elipses) => {
124                 let path = try_opt!(rewrite_path(context, true, None, path, width, offset));
125
126                 let (elipses_str, terminator) = if elipses {
127                     (", ..", "..")
128                 } else {
129                     ("", "}")
130                 };
131
132                 // 5 = `{` plus space before and after plus `}` plus space before.
133                 let budget = try_opt!(width.checked_sub(path.len() + 5 + elipses_str.len()));
134                 // FIXME Using visual indenting, should use block or visual to match
135                 // struct lit preference (however, in practice I think it is rare
136                 // for struct patterns to be multi-line).
137                 // 3 = `{` plus space before and after.
138                 let offset = offset + path.len() + 3;
139
140                 let items = itemize_list(context.codemap,
141                                          fields.iter(),
142                                          terminator,
143                                          |f| f.span.lo,
144                                          |f| f.span.hi,
145                                          |f| f.node.rewrite(context, budget, offset),
146                                          context.codemap.span_after(self.span, "{"),
147                                          self.span.hi);
148                 let mut field_string = try_opt!(format_item_list(items,
149                                                                  budget,
150                                                                  offset,
151                                                                  context.config));
152                 if elipses {
153                     if field_string.contains('\n') {
154                         field_string.push_str(",\n");
155                         field_string.push_str(&offset.to_string(context.config));
156                         field_string.push_str("..");
157                     } else {
158                         if field_string.len() > 0 {
159                             field_string.push_str(", ");
160                         }
161                         field_string.push_str("..");
162                     }
163                 }
164
165                 if field_string.is_empty() {
166                     Some(format!("{} {{}}", path))
167                 } else {
168                     Some(format!("{} {{ {} }}", path, field_string))
169                 }
170             }
171             // FIXME(#819) format pattern macros.
172             PatKind::Mac(..) => {
173                 wrap_str(context.snippet(self.span),
174                          context.config.max_width,
175                          width,
176                          offset)
177             }
178         }
179     }
180 }
181
182 impl Rewrite for FieldPat {
183     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
184         let pat = self.pat.rewrite(context, width, offset);
185         if self.is_shorthand {
186             pat
187         } else {
188             wrap_str(format!("{}: {}", self.ident.to_string(), try_opt!(pat)),
189                      context.config.max_width,
190                      width,
191                      offset)
192         }
193     }
194 }