]> git.lizzy.rs Git - rust.git/blob - src/patterns.rs
Merge pull request #2138 from topecongiro/comments-around-trait-bounds
[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, RangeSyntax};
12 use syntax::codemap::{self, BytePos, Span};
13 use syntax::ptr;
14
15 use spanned::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, PairParts};
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 shape::Shape;
24 use types::{rewrite_path, PathContext};
25 use utils::{format_mutability, mk_sp};
26
27 impl Rewrite for Pat {
28     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
29         match self.node {
30             PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, shape),
31             PatKind::Ident(binding_mode, ident, ref sub_pat) => {
32                 let (prefix, mutability) = match binding_mode {
33                     BindingMode::ByRef(mutability) => ("ref ", mutability),
34                     BindingMode::ByValue(mutability) => ("", mutability),
35                 };
36                 let mut_infix = format_mutability(mutability);
37                 let id_str = ident.node.to_string();
38                 let sub_pat = match *sub_pat {
39                     Some(ref p) => {
40                         // 3 - ` @ `.
41                         let width = shape
42                             .width
43                             .checked_sub(prefix.len() + mut_infix.len() + id_str.len() + 3)?;
44                         format!(
45                             " @ {}",
46                             p.rewrite(context, Shape::legacy(width, shape.indent))?
47                         )
48                     }
49                     None => "".to_owned(),
50                 };
51
52                 Some(format!("{}{}{}{}", prefix, mut_infix, id_str, sub_pat))
53             }
54             PatKind::Wild => if 1 <= shape.width {
55                 Some("_".to_owned())
56             } else {
57                 None
58             },
59             PatKind::Range(ref lhs, ref rhs, ref end_kind) => {
60                 let infix = match *end_kind {
61                     RangeEnd::Included(RangeSyntax::DotDotDot) => "...",
62                     RangeEnd::Included(RangeSyntax::DotDotEq) => "..=",
63                     RangeEnd::Excluded => "..",
64                 };
65                 rewrite_pair(
66                     &**lhs,
67                     &**rhs,
68                     PairParts::new("", infix, ""),
69                     context,
70                     shape,
71                     SeparatorPlace::Front,
72                 )
73             }
74             PatKind::Ref(ref pat, mutability) => {
75                 let prefix = format!("&{}", format_mutability(mutability));
76                 rewrite_unary_prefix(context, &prefix, &**pat, shape)
77             }
78             PatKind::Tuple(ref items, dotdot_pos) => {
79                 rewrite_tuple_pat(items, dotdot_pos, None, self.span, context, shape)
80             }
81             PatKind::Path(ref q_self, ref path) => {
82                 rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)
83             }
84             PatKind::TupleStruct(ref path, ref pat_vec, dotdot_pos) => {
85                 let path_str = rewrite_path(context, PathContext::Expr, None, path, shape)?;
86                 rewrite_tuple_pat(
87                     pat_vec,
88                     dotdot_pos,
89                     Some(path_str),
90                     self.span,
91                     context,
92                     shape,
93                 )
94             }
95             PatKind::Lit(ref expr) => expr.rewrite(context, shape),
96             PatKind::Slice(ref prefix, ref slice_pat, ref suffix) => {
97                 // Rewrite all the sub-patterns.
98                 let prefix = prefix.iter().map(|p| p.rewrite(context, shape));
99                 let slice_pat = slice_pat
100                     .as_ref()
101                     .map(|p| Some(format!("{}..", p.rewrite(context, shape)?)));
102                 let suffix = suffix.iter().map(|p| p.rewrite(context, shape));
103
104                 // Munge them together.
105                 let pats: Option<Vec<String>> =
106                     prefix.chain(slice_pat.into_iter()).chain(suffix).collect();
107
108                 // Check that all the rewrites succeeded, and if not return None.
109                 let pats = pats?;
110
111                 // Unwrap all the sub-strings and join them with commas.
112                 let result = if context.config.spaces_within_square_brackets() {
113                     format!("[ {} ]", pats.join(", "))
114                 } else {
115                     format!("[{}]", pats.join(", "))
116                 };
117                 Some(result)
118             }
119             PatKind::Struct(ref path, ref fields, ellipsis) => {
120                 rewrite_struct_pat(path, fields, ellipsis, self.span, context, shape)
121             }
122             // FIXME(#819) format pattern macros.
123             PatKind::Mac(..) => Some(context.snippet(self.span)),
124         }
125     }
126 }
127
128 fn rewrite_struct_pat(
129     path: &ast::Path,
130     fields: &[codemap::Spanned<ast::FieldPat>],
131     ellipsis: bool,
132     span: Span,
133     context: &RewriteContext,
134     shape: Shape,
135 ) -> Option<String> {
136     // 2 =  ` {`
137     let path_shape = shape.sub_width(2)?;
138     let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
139
140     if fields.is_empty() && !ellipsis {
141         return Some(format!("{} {{}}", path_str));
142     }
143
144     let (ellipsis_str, terminator) = if ellipsis { (", ..", "..") } else { ("", "}") };
145
146     // 3 = ` { `, 2 = ` }`.
147     let (h_shape, v_shape) =
148         struct_lit_shape(shape, context, path_str.len() + 3, ellipsis_str.len() + 2)?;
149
150     let items = itemize_list(
151         context.codemap,
152         fields.iter(),
153         terminator,
154         |f| f.span.lo(),
155         |f| f.span.hi(),
156         |f| f.node.rewrite(context, v_shape),
157         context.codemap.span_after(span, "{"),
158         span.hi(),
159         false,
160     );
161     let item_vec = items.collect::<Vec<_>>();
162
163     let tactic = struct_lit_tactic(h_shape, context, &item_vec);
164     let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
165     let fmt = struct_lit_formatting(nested_shape, tactic, context, false);
166
167     let mut fields_str = write_list(&item_vec, &fmt)?;
168     let one_line_width = h_shape.map_or(0, |shape| shape.width);
169
170     if ellipsis {
171         if fields_str.contains('\n') || fields_str.len() > one_line_width {
172             // Add a missing trailing comma.
173             if fmt.trailing_separator == SeparatorTactic::Never {
174                 fields_str.push_str(",");
175             }
176             fields_str.push_str("\n");
177             fields_str.push_str(&nested_shape.indent.to_string(context.config));
178             fields_str.push_str("..");
179         } else {
180             if !fields_str.is_empty() {
181                 // there are preceding struct fields being matched on
182                 if fmt.tactic == DefinitiveListTactic::Vertical {
183                     // if the tactic is Vertical, write_list already added a trailing ,
184                     fields_str.push_str(" ");
185                 } else {
186                     fields_str.push_str(", ");
187                 }
188             }
189             fields_str.push_str("..");
190         }
191     }
192
193     let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
194     Some(format!("{} {{{}}}", path_str, fields_str))
195 }
196
197 impl Rewrite for FieldPat {
198     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
199         let pat = self.pat.rewrite(context, shape);
200         if self.is_shorthand {
201             pat
202         } else {
203             let pat_str = pat?;
204             let id_str = self.ident.to_string();
205             let one_line_width = id_str.len() + 2 + pat_str.len();
206             if one_line_width <= shape.width {
207                 Some(format!("{}: {}", id_str, pat_str))
208             } else {
209                 let nested_shape = shape.block_indent(context.config.tab_spaces());
210                 let pat_str = self.pat.rewrite(context, nested_shape)?;
211                 Some(format!(
212                     "{}:\n{}{}",
213                     id_str,
214                     nested_shape.indent.to_string(context.config),
215                     pat_str,
216                 ))
217             }
218         }
219     }
220 }
221
222 pub 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(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(p) => p.span(),
240             TuplePatField::Dotdot(span) => span,
241         }
242     }
243 }
244
245 pub fn can_be_overflowed_pat(context: &RewriteContext, pat: &TuplePatField, len: usize) -> bool {
246     match *pat {
247         TuplePatField::Pat(pat) => match pat.node {
248             ast::PatKind::Path(..) |
249             ast::PatKind::Tuple(..) |
250             ast::PatKind::Struct(..) |
251             ast::PatKind::TupleStruct(..) => context.use_block_indent() && len == 1,
252             ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => {
253                 can_be_overflowed_pat(context, &TuplePatField::Pat(p), len)
254             }
255             ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
256             _ => false,
257         },
258         TuplePatField::Dotdot(..) => false,
259     }
260 }
261
262 fn rewrite_tuple_pat(
263     pats: &[ptr::P<ast::Pat>],
264     dotdot_pos: Option<usize>,
265     path_str: Option<String>,
266     span: Span,
267     context: &RewriteContext,
268     shape: Shape,
269 ) -> Option<String> {
270     let mut pat_vec: Vec<_> = pats.into_iter().map(|x| TuplePatField::Pat(x)).collect();
271
272     if let Some(pos) = dotdot_pos {
273         let prev = if pos == 0 {
274             span.lo()
275         } else {
276             pats[pos - 1].span().hi()
277         };
278         let next = if pos + 1 >= pats.len() {
279             span.hi()
280         } else {
281             pats[pos + 1].span().lo()
282         };
283         let dot_span = mk_sp(prev, next);
284         let snippet = context.snippet(dot_span);
285         let lo = dot_span.lo() + BytePos(snippet.find_uncommented("..").unwrap() as u32);
286         let dotdot = TuplePatField::Dotdot(Span::new(
287             lo,
288             // 2 == "..".len()
289             lo + BytePos(2),
290             codemap::NO_EXPANSION,
291         ));
292         pat_vec.insert(pos, dotdot);
293     }
294
295     if pat_vec.is_empty() {
296         return Some(format!("{}()", path_str.unwrap_or_default()));
297     }
298
299     let wildcard_suffix_len = count_wildcard_suffix_len(context, &pat_vec, span, shape);
300     let (pat_vec, span) = if context.config.condense_wildcard_suffixes() && wildcard_suffix_len >= 2
301     {
302         let new_item_count = 1 + pat_vec.len() - wildcard_suffix_len;
303         let sp = pat_vec[new_item_count - 1].span();
304         let snippet = context.snippet(sp);
305         let lo = sp.lo() + BytePos(snippet.find_uncommented("_").unwrap() as u32);
306         pat_vec[new_item_count - 1] = TuplePatField::Dotdot(mk_sp(lo, lo + BytePos(1)));
307         (
308             &pat_vec[..new_item_count],
309             mk_sp(span.lo(), lo + BytePos(1)),
310         )
311     } else {
312         (&pat_vec[..], span)
313     };
314
315     // add comma if `(x,)`
316     let add_comma = path_str.is_none() && pat_vec.len() == 1 && dotdot_pos.is_none();
317     let mut context = context.clone();
318     if let Some(&TuplePatField::Dotdot(..)) = pat_vec.last() {
319         context.inside_macro = true;
320     }
321     let path_str = path_str.unwrap_or_default();
322     let mut pat_ref_vec = Vec::with_capacity(pat_vec.len());
323     for pat in pat_vec {
324         pat_ref_vec.push(pat);
325     }
326
327     rewrite_call_inner(
328         &context,
329         &path_str,
330         &pat_ref_vec[..],
331         span,
332         shape,
333         shape.width,
334         add_comma,
335     )
336 }
337
338 fn count_wildcard_suffix_len(
339     context: &RewriteContext,
340     patterns: &[TuplePatField],
341     span: Span,
342     shape: Shape,
343 ) -> usize {
344     let mut suffix_len = 0;
345
346     let items: Vec<_> = itemize_list(
347         context.codemap,
348         patterns.iter(),
349         ")",
350         |item| item.span().lo(),
351         |item| item.span().hi(),
352         |item| item.rewrite(context, shape),
353         context.codemap.span_after(span, "("),
354         span.hi() - BytePos(1),
355         false,
356     ).collect();
357
358     for item in items.iter().rev().take_while(|i| match i.item {
359         Some(ref internal_string) if internal_string == "_" => true,
360         _ => false,
361     }) {
362         suffix_len += 1;
363
364         if item.pre_comment.is_some() || item.post_comment.is_some() {
365             break;
366         }
367     }
368
369     suffix_len
370 }