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