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