]> git.lizzy.rs Git - rust.git/blob - src/patterns.rs
default required-version to the current rustfmt version
[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};
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                     "",
69                     infix,
70                     "",
71                     context,
72                     shape,
73                     SeparatorPlace::Front,
74                 )
75             }
76             PatKind::Ref(ref pat, mutability) => {
77                 let prefix = format!("&{}", format_mutability(mutability));
78                 rewrite_unary_prefix(context, &prefix, &**pat, shape)
79             }
80             PatKind::Tuple(ref items, dotdot_pos) => {
81                 rewrite_tuple_pat(items, dotdot_pos, None, self.span, context, shape)
82             }
83             PatKind::Path(ref q_self, ref path) => {
84                 rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)
85             }
86             PatKind::TupleStruct(ref path, ref pat_vec, dotdot_pos) => {
87                 let path_str = rewrite_path(context, PathContext::Expr, None, path, shape)?;
88                 rewrite_tuple_pat(
89                     pat_vec,
90                     dotdot_pos,
91                     Some(path_str),
92                     self.span,
93                     context,
94                     shape,
95                 )
96             }
97             PatKind::Lit(ref expr) => expr.rewrite(context, shape),
98             PatKind::Slice(ref prefix, ref slice_pat, ref suffix) => {
99                 // Rewrite all the sub-patterns.
100                 let prefix = prefix.iter().map(|p| p.rewrite(context, shape));
101                 let slice_pat = slice_pat
102                     .as_ref()
103                     .map(|p| Some(format!("{}..", p.rewrite(context, shape)?)));
104                 let suffix = suffix.iter().map(|p| p.rewrite(context, shape));
105
106                 // Munge them together.
107                 let pats: Option<Vec<String>> =
108                     prefix.chain(slice_pat.into_iter()).chain(suffix).collect();
109
110                 // Check that all the rewrites succeeded, and if not return None.
111                 let pats = pats?;
112
113                 // Unwrap all the sub-strings and join them with commas.
114                 let result = if context.config.spaces_within_square_brackets() {
115                     format!("[ {} ]", pats.join(", "))
116                 } else {
117                     format!("[{}]", pats.join(", "))
118                 };
119                 Some(result)
120             }
121             PatKind::Struct(ref path, ref fields, elipses) => {
122                 rewrite_struct_pat(path, fields, elipses, self.span, context, shape)
123             }
124             // FIXME(#819) format pattern macros.
125             PatKind::Mac(..) => Some(context.snippet(self.span)),
126         }
127     }
128 }
129
130 fn rewrite_struct_pat(
131     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 = shape.sub_width(2)?;
140     let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
141
142     if fields.is_empty() && !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         struct_lit_shape(shape, context, path_str.len() + 3, elipses_str.len() + 2)?;
151
152     let items = itemize_list(
153         context.codemap,
154         fields.iter(),
155         terminator,
156         |f| f.span.lo(),
157         |f| f.span.hi(),
158         |f| f.node.rewrite(context, v_shape),
159         context.codemap.span_after(span, "{"),
160         span.hi(),
161         false,
162     );
163     let item_vec = items.collect::<Vec<_>>();
164
165     let tactic = struct_lit_tactic(h_shape, context, &item_vec);
166     let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
167     let fmt = struct_lit_formatting(nested_shape, tactic, context, false);
168
169     let mut fields_str = write_list(&item_vec, &fmt)?;
170     let one_line_width = h_shape.map_or(0, |shape| shape.width);
171
172     if elipses {
173         if fields_str.contains('\n') || fields_str.len() > one_line_width {
174             // Add a missing trailing comma.
175             if fmt.trailing_separator == SeparatorTactic::Never {
176                 fields_str.push_str(",");
177             }
178             fields_str.push_str("\n");
179             fields_str.push_str(&nested_shape.indent.to_string(context.config));
180             fields_str.push_str("..");
181         } else {
182             if !fields_str.is_empty() {
183                 // there are preceeding struct fields being matched on
184                 if fmt.tactic == DefinitiveListTactic::Vertical {
185                     // if the tactic is Vertical, write_list already added a trailing ,
186                     fields_str.push_str(" ");
187                 } else {
188                     fields_str.push_str(", ");
189                 }
190             }
191             fields_str.push_str("..");
192         }
193     }
194
195     let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
196     Some(format!("{} {{{}}}", path_str, fields_str))
197 }
198
199 impl Rewrite for FieldPat {
200     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
201         let pat = self.pat.rewrite(context, shape);
202         if self.is_shorthand {
203             pat
204         } else {
205             let pat_str = pat?;
206             let id_str = self.ident.to_string();
207             let one_line_width = id_str.len() + 2 + pat_str.len();
208             if one_line_width <= shape.width {
209                 Some(format!("{}: {}", id_str, pat_str))
210             } else {
211                 let nested_shape = shape.block_indent(context.config.tab_spaces());
212                 let pat_str = self.pat.rewrite(context, nested_shape)?;
213                 Some(format!(
214                     "{}:\n{}{}",
215                     id_str,
216                     nested_shape.indent.to_string(context.config),
217                     pat_str,
218                 ))
219             }
220         }
221     }
222 }
223
224 pub enum TuplePatField<'a> {
225     Pat(&'a ptr::P<ast::Pat>),
226     Dotdot(Span),
227 }
228
229 impl<'a> Rewrite for TuplePatField<'a> {
230     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
231         match *self {
232             TuplePatField::Pat(p) => p.rewrite(context, shape),
233             TuplePatField::Dotdot(_) => Some("..".to_string()),
234         }
235     }
236 }
237
238 impl<'a> Spanned for TuplePatField<'a> {
239     fn span(&self) -> Span {
240         match *self {
241             TuplePatField::Pat(p) => p.span(),
242             TuplePatField::Dotdot(span) => span,
243         }
244     }
245 }
246
247 pub fn can_be_overflowed_pat(context: &RewriteContext, pat: &TuplePatField, len: usize) -> bool {
248     match *pat {
249         TuplePatField::Pat(pat) => match pat.node {
250             ast::PatKind::Path(..) | ast::PatKind::Tuple(..) | ast::PatKind::Struct(..) => {
251                 context.use_block_indent() && len == 1
252             }
253             ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => {
254                 can_be_overflowed_pat(context, &TuplePatField::Pat(p), len)
255             }
256             ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
257             _ => false,
258         },
259         TuplePatField::Dotdot(..) => false,
260     }
261 }
262
263 fn rewrite_tuple_pat(
264     pats: &[ptr::P<ast::Pat>],
265     dotdot_pos: Option<usize>,
266     path_str: Option<String>,
267     span: Span,
268     context: &RewriteContext,
269     shape: Shape,
270 ) -> Option<String> {
271     let mut pat_vec: Vec<_> = pats.into_iter().map(|x| TuplePatField::Pat(x)).collect();
272
273     if let Some(pos) = dotdot_pos {
274         let prev = if pos == 0 {
275             span.lo()
276         } else {
277             pats[pos - 1].span().hi()
278         };
279         let next = if pos + 1 >= pats.len() {
280             span.hi()
281         } else {
282             pats[pos + 1].span().lo()
283         };
284         let dot_span = mk_sp(prev, next);
285         let snippet = context.snippet(dot_span);
286         let lo = dot_span.lo() + BytePos(snippet.find_uncommented("..").unwrap() as u32);
287         let dotdot = TuplePatField::Dotdot(Span::new(
288             lo,
289             // 2 == "..".len()
290             lo + BytePos(2),
291             codemap::NO_EXPANSION,
292         ));
293         pat_vec.insert(pos, dotdot);
294     }
295
296     if pat_vec.is_empty() {
297         return Some(format!("{}()", path_str.unwrap_or_default()));
298     }
299
300     let wildcard_suffix_len = count_wildcard_suffix_len(context, &pat_vec, span, shape);
301     let (pat_vec, span) = if context.config.condense_wildcard_suffixes() && wildcard_suffix_len >= 2
302     {
303         let new_item_count = 1 + pat_vec.len() - wildcard_suffix_len;
304         let sp = pat_vec[new_item_count - 1].span();
305         let snippet = context.snippet(sp);
306         let lo = sp.lo() + BytePos(snippet.find_uncommented("_").unwrap() as u32);
307         pat_vec[new_item_count - 1] = TuplePatField::Dotdot(mk_sp(lo, lo + BytePos(1)));
308         (
309             &pat_vec[..new_item_count],
310             mk_sp(span.lo(), lo + BytePos(1)),
311         )
312     } else {
313         (&pat_vec[..], span)
314     };
315
316     // add comma if `(x,)`
317     let add_comma = path_str.is_none() && pat_vec.len() == 1 && dotdot_pos.is_none();
318     let mut context = context.clone();
319     if let Some(&TuplePatField::Dotdot(..)) = pat_vec.last() {
320         context.inside_macro = true;
321     }
322     let path_str = path_str.unwrap_or_default();
323     let mut pat_ref_vec = Vec::with_capacity(pat_vec.len());
324     for pat in pat_vec {
325         pat_ref_vec.push(pat);
326     }
327
328     rewrite_call_inner(
329         &context,
330         &path_str,
331         &pat_ref_vec[..],
332         span,
333         shape,
334         shape.width,
335         add_comma,
336     )
337 }
338
339 fn count_wildcard_suffix_len(
340     context: &RewriteContext,
341     patterns: &[TuplePatField],
342     span: Span,
343     shape: Shape,
344 ) -> usize {
345     let mut suffix_len = 0;
346
347     let items: Vec<_> = itemize_list(
348         context.codemap,
349         patterns.iter(),
350         ")",
351         |item| item.span().lo(),
352         |item| item.span().hi(),
353         |item| item.rewrite(context, shape),
354         context.codemap.span_after(span, "("),
355         span.hi() - BytePos(1),
356         false,
357     ).collect();
358
359     for item in items.iter().rev().take_while(|i| match i.item {
360         Some(ref internal_string) if internal_string == "_" => true,
361         _ => false,
362     }) {
363         suffix_len += 1;
364
365         if item.pre_comment.is_some() || item.post_comment.is_some() {
366             break;
367         }
368     }
369
370     suffix_len
371 }