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.
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.
12 use syntax::ast::{self, BindingMode, FieldPat, Pat, PatKind, RangeEnd, RangeSyntax};
13 use syntax::codemap::{self, BytePos, Span};
16 use codemap::SpanUtils;
17 use comment::FindUncommented;
19 can_be_overflowed_expr, rewrite_pair, rewrite_unary_prefix, wrap_struct_field, PairParts,
22 itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape, struct_lit_tactic,
25 use macros::{rewrite_macro, MacroPosition};
27 use rewrite::{Rewrite, RewriteContext};
30 use types::{rewrite_path, PathContext};
31 use utils::{format_mutability, mk_sp};
33 /// Returns true if the given pattern is short. A short pattern is defined by the following grammer:
37 /// - `&[single-line, ntp]`
41 /// - unary tuple constructor `([small, ntp])`
43 pub fn is_short_pattern(pat: &ast::Pat, pat_str: &str) -> bool {
44 // We also require that the pattern is reasonably 'small' with its literal width.
45 pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(pat)
48 fn is_short_pattern_inner(pat: &ast::Pat) -> bool {
50 ast::PatKind::Wild | ast::PatKind::Lit(_) => true,
51 ast::PatKind::Ident(_, _, ref pat) => pat.is_none(),
52 ast::PatKind::Struct(..)
53 | ast::PatKind::Mac(..)
54 | ast::PatKind::Slice(..)
55 | ast::PatKind::Path(..)
56 | ast::PatKind::Range(..) => false,
57 ast::PatKind::Tuple(ref subpats, _) => subpats.len() <= 1,
58 ast::PatKind::TupleStruct(ref path, ref subpats, _) => {
59 path.segments.len() <= 1 && subpats.len() <= 1
61 ast::PatKind::Box(ref p) | ast::PatKind::Ref(ref p, _) | ast::PatKind::Paren(ref p) => {
62 is_short_pattern_inner(&*p)
67 impl Rewrite for Pat {
68 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
70 PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, shape),
71 PatKind::Ident(binding_mode, ident, ref sub_pat) => {
72 let (prefix, mutability) = match binding_mode {
73 BindingMode::ByRef(mutability) => ("ref ", mutability),
74 BindingMode::ByValue(mutability) => ("", mutability),
76 let mut_infix = format_mutability(mutability);
77 let id_str = ident.name.to_string();
78 let sub_pat = match *sub_pat {
83 .checked_sub(prefix.len() + mut_infix.len() + id_str.len() + 3)?;
86 p.rewrite(context, Shape::legacy(width, shape.indent))?
89 None => "".to_owned(),
92 Some(format!("{}{}{}{}", prefix, mut_infix, id_str, sub_pat))
101 PatKind::Range(ref lhs, ref rhs, ref end_kind) => {
102 let infix = match *end_kind {
103 RangeEnd::Included(RangeSyntax::DotDotDot) => "...",
104 RangeEnd::Included(RangeSyntax::DotDotEq) => "..=",
105 RangeEnd::Excluded => "..",
107 let infix = if context.config.spaces_around_ranges() {
108 format!(" {} ", infix)
115 PairParts::new("", &infix, ""),
118 SeparatorPlace::Front,
121 PatKind::Ref(ref pat, mutability) => {
122 let prefix = format!("&{}", format_mutability(mutability));
123 rewrite_unary_prefix(context, &prefix, &**pat, shape)
125 PatKind::Tuple(ref items, dotdot_pos) => {
126 rewrite_tuple_pat(items, dotdot_pos, None, self.span, context, shape)
128 PatKind::Path(ref q_self, ref path) => {
129 rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)
131 PatKind::TupleStruct(ref path, ref pat_vec, dotdot_pos) => {
132 let path_str = rewrite_path(context, PathContext::Expr, None, path, shape)?;
142 PatKind::Lit(ref expr) => expr.rewrite(context, shape),
143 PatKind::Slice(ref prefix, ref slice_pat, ref suffix) => {
144 // Rewrite all the sub-patterns.
145 let prefix = prefix.iter().map(|p| p.rewrite(context, shape));
146 let slice_pat = slice_pat
148 .map(|p| Some(format!("{}..", p.rewrite(context, shape)?)));
149 let suffix = suffix.iter().map(|p| p.rewrite(context, shape));
151 // Munge them together.
152 let pats: Option<Vec<String>> =
153 prefix.chain(slice_pat.into_iter()).chain(suffix).collect();
155 // Check that all the rewrites succeeded, and if not return None.
158 // Unwrap all the sub-strings and join them with commas.
159 let result = if context.config.spaces_within_parens_and_brackets() {
160 format!("[ {} ]", pats.join(", "))
162 format!("[{}]", pats.join(", "))
166 PatKind::Struct(ref path, ref fields, ellipsis) => {
167 rewrite_struct_pat(path, fields, ellipsis, self.span, context, shape)
169 PatKind::Mac(ref mac) => rewrite_macro(mac, None, context, shape, MacroPosition::Pat),
170 PatKind::Paren(ref pat) => pat.rewrite(context, shape.offset_left(1)?.sub_width(1)?)
171 .map(|inner_pat| format!("({})", inner_pat)),
176 fn rewrite_struct_pat(
178 fields: &[codemap::Spanned<ast::FieldPat>],
181 context: &RewriteContext,
183 ) -> Option<String> {
185 let path_shape = shape.sub_width(2)?;
186 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
188 if fields.is_empty() && !ellipsis {
189 return Some(format!("{} {{}}", path_str));
192 let (ellipsis_str, terminator) = if ellipsis { (", ..", "..") } else { ("", "}") };
194 // 3 = ` { `, 2 = ` }`.
195 let (h_shape, v_shape) =
196 struct_lit_shape(shape, context, path_str.len() + 3, ellipsis_str.len() + 2)?;
198 let items = itemize_list(
199 context.snippet_provider,
205 |f| f.node.rewrite(context, v_shape),
206 context.snippet_provider.span_after(span, "{"),
210 let item_vec = items.collect::<Vec<_>>();
212 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
213 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
214 let fmt = struct_lit_formatting(nested_shape, tactic, context, false);
216 let mut fields_str = write_list(&item_vec, &fmt)?;
217 let one_line_width = h_shape.map_or(0, |shape| shape.width);
220 if fields_str.contains('\n') || fields_str.len() > one_line_width {
221 // Add a missing trailing comma.
222 if fmt.trailing_separator == SeparatorTactic::Never {
223 fields_str.push_str(",");
225 fields_str.push_str("\n");
226 fields_str.push_str(&nested_shape.indent.to_string(context.config));
227 fields_str.push_str("..");
229 if !fields_str.is_empty() {
230 // there are preceding struct fields being matched on
231 if fmt.tactic == DefinitiveListTactic::Vertical {
232 // if the tactic is Vertical, write_list already added a trailing ,
233 fields_str.push_str(" ");
235 fields_str.push_str(", ");
238 fields_str.push_str("..");
242 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
243 Some(format!("{} {{{}}}", path_str, fields_str))
246 impl Rewrite for FieldPat {
247 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
248 let pat = self.pat.rewrite(context, shape);
249 if self.is_shorthand {
253 let id_str = self.ident.to_string();
254 let one_line_width = id_str.len() + 2 + pat_str.len();
255 if one_line_width <= shape.width {
256 Some(format!("{}: {}", id_str, pat_str))
258 let nested_shape = shape.block_indent(context.config.tab_spaces());
259 let pat_str = self.pat.rewrite(context, nested_shape)?;
263 nested_shape.indent.to_string(context.config),
271 pub enum TuplePatField<'a> {
272 Pat(&'a ptr::P<ast::Pat>),
276 impl<'a> Rewrite for TuplePatField<'a> {
277 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
279 TuplePatField::Pat(p) => p.rewrite(context, shape),
280 TuplePatField::Dotdot(_) => Some("..".to_string()),
285 impl<'a> Spanned for TuplePatField<'a> {
286 fn span(&self) -> Span {
288 TuplePatField::Pat(p) => p.span(),
289 TuplePatField::Dotdot(span) => span,
294 pub fn can_be_overflowed_pat(context: &RewriteContext, pat: &TuplePatField, len: usize) -> bool {
296 TuplePatField::Pat(pat) => match pat.node {
297 ast::PatKind::Path(..)
298 | ast::PatKind::Tuple(..)
299 | ast::PatKind::Struct(..)
300 | ast::PatKind::TupleStruct(..) => context.use_block_indent() && len == 1,
301 ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => {
302 can_be_overflowed_pat(context, &TuplePatField::Pat(p), len)
304 ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
307 TuplePatField::Dotdot(..) => false,
311 fn rewrite_tuple_pat(
312 pats: &[ptr::P<ast::Pat>],
313 dotdot_pos: Option<usize>,
314 path_str: Option<String>,
316 context: &RewriteContext,
318 ) -> Option<String> {
319 let mut pat_vec: Vec<_> = pats.into_iter().map(|x| TuplePatField::Pat(x)).collect();
321 if let Some(pos) = dotdot_pos {
322 let prev = if pos == 0 {
325 pats[pos - 1].span().hi()
327 let next = if pos + 1 >= pats.len() {
330 pats[pos + 1].span().lo()
332 let dot_span = mk_sp(prev, next);
333 let snippet = context.snippet(dot_span);
334 let lo = dot_span.lo() + BytePos(snippet.find_uncommented("..").unwrap() as u32);
335 let dotdot = TuplePatField::Dotdot(Span::new(
339 codemap::NO_EXPANSION,
341 pat_vec.insert(pos, dotdot);
344 if pat_vec.is_empty() {
345 return Some(format!("{}()", path_str.unwrap_or_default()));
348 let wildcard_suffix_len = count_wildcard_suffix_len(context, &pat_vec, span, shape);
349 let (pat_vec, span) = if context.config.condense_wildcard_suffixes() && wildcard_suffix_len >= 2
351 let new_item_count = 1 + pat_vec.len() - wildcard_suffix_len;
352 let sp = pat_vec[new_item_count - 1].span();
353 let snippet = context.snippet(sp);
354 let lo = sp.lo() + BytePos(snippet.find_uncommented("_").unwrap() as u32);
355 pat_vec[new_item_count - 1] = TuplePatField::Dotdot(mk_sp(lo, lo + BytePos(1)));
357 &pat_vec[..new_item_count],
358 mk_sp(span.lo(), lo + BytePos(1)),
364 // add comma if `(x,)`
365 let add_comma = path_str.is_none() && pat_vec.len() == 1 && dotdot_pos.is_none();
366 let path_str = path_str.unwrap_or_default();
367 let pat_ref_vec = pat_vec.iter().collect::<Vec<_>>();
369 overflow::rewrite_with_parens(
375 context.config.max_width(),
377 Some(SeparatorTactic::Always)
384 fn count_wildcard_suffix_len(
385 context: &RewriteContext,
386 patterns: &[TuplePatField],
390 let mut suffix_len = 0;
392 let items: Vec<_> = itemize_list(
393 context.snippet_provider,
397 |item| item.span().lo(),
398 |item| item.span().hi(),
399 |item| item.rewrite(context, shape),
400 context.snippet_provider.span_after(span, "("),
401 span.hi() - BytePos(1),
405 for item in items.iter().rev().take_while(|i| match i.item {
406 Some(ref internal_string) if internal_string == "_" => true,
411 if item.has_comment() {