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