1 use rustc_span::{BytePos, Span};
2 use syntax::ast::{self, BindingMode, FieldPat, Pat, PatKind, RangeEnd, RangeSyntax};
5 use crate::comment::{combine_strs_with_missing_comments, FindUncommented};
6 use crate::config::lists::*;
7 use crate::expr::{can_be_overflowed_expr, rewrite_unary_prefix, wrap_struct_field};
9 definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
10 struct_lit_tactic, write_list, ListFormatting, ListItem, Separator,
12 use crate::macros::{rewrite_macro, MacroPosition};
14 use crate::pairs::{rewrite_pair, PairParts};
15 use crate::rewrite::{Rewrite, RewriteContext};
16 use crate::shape::Shape;
17 use crate::source_map::SpanUtils;
18 use crate::spanned::Spanned;
19 use crate::types::{rewrite_path, PathContext};
20 use crate::utils::{format_mutability, mk_sp, rewrite_ident};
22 /// Returns `true` if the given pattern is "short".
23 /// A short pattern is defined by the following grammar:
27 /// - `&[single-line, ntp]`
31 /// - unary tuple constructor `([small, ntp])`
33 pub(crate) fn is_short_pattern(pat: &ast::Pat, pat_str: &str) -> bool {
34 // We also require that the pattern is reasonably 'small' with its literal width.
35 pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(pat)
38 fn is_short_pattern_inner(pat: &ast::Pat) -> bool {
40 ast::PatKind::Rest | ast::PatKind::Wild | ast::PatKind::Lit(_) => true,
41 ast::PatKind::Ident(_, _, ref pat) => pat.is_none(),
42 ast::PatKind::Struct(..)
43 | ast::PatKind::MacCall(..)
44 | ast::PatKind::Slice(..)
45 | ast::PatKind::Path(..)
46 | ast::PatKind::Range(..) => false,
47 ast::PatKind::Tuple(ref subpats) => subpats.len() <= 1,
48 ast::PatKind::TupleStruct(ref path, ref subpats) => {
49 path.segments.len() <= 1 && subpats.len() <= 1
51 ast::PatKind::Box(ref p) | ast::PatKind::Ref(ref p, _) | ast::PatKind::Paren(ref p) => {
52 is_short_pattern_inner(&*p)
54 PatKind::Or(ref pats) => pats.iter().all(|p| is_short_pattern_inner(p)),
58 impl Rewrite for Pat {
59 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
61 PatKind::Or(ref pats) => {
64 .map(|p| p.rewrite(context, shape))
65 .collect::<Option<Vec<_>>>()?;
67 let use_mixed_layout = pats
70 .all(|(pat, pat_str)| is_short_pattern(pat, pat_str));
71 let items: Vec<_> = pat_strs.into_iter().map(ListItem::from_str).collect();
72 let tactic = if use_mixed_layout {
73 DefinitiveListTactic::Mixed
77 ListTactic::HorizontalVertical,
78 Separator::VerticalBar,
82 let fmt = ListFormatting::new(shape, context.config)
85 .separator_place(context.config.binop_separator())
86 .ends_with_newline(false);
87 write_list(&items, &fmt)
89 PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, shape),
90 PatKind::Ident(binding_mode, ident, ref sub_pat) => {
91 let (prefix, mutability) = match binding_mode {
92 BindingMode::ByRef(mutability) => ("ref", mutability),
93 BindingMode::ByValue(mutability) => ("", mutability),
95 let mut_infix = format_mutability(mutability).trim();
96 let id_str = rewrite_ident(context, ident);
97 let sub_pat = match *sub_pat {
102 .checked_sub(prefix.len() + mut_infix.len() + id_str.len() + 2)?;
103 let lo = context.snippet_provider.span_after(self.span, "@");
104 combine_strs_with_missing_comments(
107 &p.rewrite(context, Shape::legacy(width, shape.indent))?,
108 mk_sp(lo, p.span.lo()),
113 None => "".to_owned(),
116 // combine prefix and mut
117 let (first_lo, first) = if !prefix.is_empty() && !mut_infix.is_empty() {
118 let hi = context.snippet_provider.span_before(self.span, "mut");
119 let lo = context.snippet_provider.span_after(self.span, "ref");
121 context.snippet_provider.span_after(self.span, "mut"),
122 combine_strs_with_missing_comments(
131 } else if !prefix.is_empty() {
133 context.snippet_provider.span_after(self.span, "ref"),
136 } else if !mut_infix.is_empty() {
138 context.snippet_provider.span_after(self.span, "mut"),
139 mut_infix.to_owned(),
142 (self.span.lo(), "".to_owned())
145 let next = if !sub_pat.is_empty() {
146 let hi = context.snippet_provider.span_before(self.span, "@");
147 combine_strs_with_missing_comments(
151 mk_sp(ident.span.hi(), hi),
159 combine_strs_with_missing_comments(
163 mk_sp(first_lo, ident.span.lo()),
169 if 1 <= shape.width {
176 if 1 <= shape.width {
177 Some("..".to_owned())
182 PatKind::Range(ref lhs, ref rhs, ref end_kind) => match (lhs, rhs) {
183 (Some(lhs), Some(rhs)) => {
184 let infix = match end_kind.node {
185 RangeEnd::Included(RangeSyntax::DotDotDot) => "...",
186 RangeEnd::Included(RangeSyntax::DotDotEq) => "..=",
187 RangeEnd::Excluded => "..",
189 let infix = if context.config.spaces_around_ranges() {
190 format!(" {} ", infix)
197 PairParts::infix(&infix),
200 SeparatorPlace::Front,
203 (_, _) => unimplemented!(),
205 PatKind::Ref(ref pat, mutability) => {
206 let prefix = format!("&{}", format_mutability(mutability));
207 rewrite_unary_prefix(context, &prefix, &**pat, shape)
209 PatKind::Tuple(ref items) => rewrite_tuple_pat(items, None, self.span, context, shape),
210 PatKind::Path(ref q_self, ref path) => {
211 rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)
213 PatKind::TupleStruct(ref path, ref pat_vec) => {
214 let path_str = rewrite_path(context, PathContext::Expr, None, path, shape)?;
215 rewrite_tuple_pat(pat_vec, Some(path_str), self.span, context, shape)
217 PatKind::Lit(ref expr) => expr.rewrite(context, shape),
218 PatKind::Slice(ref slice_pat) => {
219 let rw: Vec<String> = slice_pat
222 if let Some(rw) = p.rewrite(context, shape) {
225 format!("{}", context.snippet(p.span))
229 Some(format!("[{}]", rw.join(", ")))
231 PatKind::Struct(ref path, ref fields, ellipsis) => {
232 rewrite_struct_pat(path, fields, ellipsis, self.span, context, shape)
234 PatKind::MacCall(ref mac) => rewrite_macro(mac, None, context, shape, MacroPosition::Pat),
235 PatKind::Paren(ref pat) => pat
236 .rewrite(context, shape.offset_left(1)?.sub_width(1)?)
237 .map(|inner_pat| format!("({})", inner_pat)),
242 fn rewrite_struct_pat(
244 fields: &[ast::FieldPat],
247 context: &RewriteContext<'_>,
249 ) -> Option<String> {
251 let path_shape = shape.sub_width(2)?;
252 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
254 if fields.is_empty() && !ellipsis {
255 return Some(format!("{} {{}}", path_str));
258 let (ellipsis_str, terminator) = if ellipsis { (", ..", "..") } else { ("", "}") };
260 // 3 = ` { `, 2 = ` }`.
261 let (h_shape, v_shape) =
262 struct_lit_shape(shape, context, path_str.len() + 3, ellipsis_str.len() + 2)?;
264 let items = itemize_list(
265 context.snippet_provider,
270 if f.attrs.is_empty() {
273 f.attrs.first().unwrap().span.lo()
277 |f| f.rewrite(context, v_shape),
278 context.snippet_provider.span_after(span, "{"),
282 let item_vec = items.collect::<Vec<_>>();
284 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
285 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
286 let fmt = struct_lit_formatting(nested_shape, tactic, context, false);
288 let mut fields_str = write_list(&item_vec, &fmt)?;
289 let one_line_width = h_shape.map_or(0, |shape| shape.width);
292 if fields_str.contains('\n') || fields_str.len() > one_line_width {
293 // Add a missing trailing comma.
294 if context.config.trailing_comma() == SeparatorTactic::Never {
295 fields_str.push_str(",");
297 fields_str.push_str("\n");
298 fields_str.push_str(&nested_shape.indent.to_string(context.config));
299 fields_str.push_str("..");
301 if !fields_str.is_empty() {
302 // there are preceding struct fields being matched on
303 if tactic == DefinitiveListTactic::Vertical {
304 // if the tactic is Vertical, write_list already added a trailing ,
305 fields_str.push_str(" ");
307 fields_str.push_str(", ");
310 fields_str.push_str("..");
314 // ast::Pat doesn't have attrs so use &[]
315 let fields_str = wrap_struct_field(context, &[], &fields_str, shape, v_shape, one_line_width)?;
316 Some(format!("{} {{{}}}", path_str, fields_str))
319 impl Rewrite for FieldPat {
320 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
321 let hi_pos = if let Some(last) = self.attrs.last() {
327 let attrs_str = if self.attrs.is_empty() {
330 self.attrs.rewrite(context, shape)?
333 let pat_str = self.pat.rewrite(context, shape)?;
334 if self.is_shorthand {
335 combine_strs_with_missing_comments(
339 mk_sp(hi_pos, self.pat.span.lo()),
344 let nested_shape = shape.block_indent(context.config.tab_spaces());
345 let id_str = rewrite_ident(context, self.ident);
346 let one_line_width = id_str.len() + 2 + pat_str.len();
347 let pat_and_id_str = if one_line_width <= shape.width {
348 format!("{}: {}", id_str, pat_str)
353 nested_shape.indent.to_string(context.config),
354 self.pat.rewrite(context, nested_shape)?
357 combine_strs_with_missing_comments(
361 mk_sp(hi_pos, self.pat.span.lo()),
370 pub(crate) enum TuplePatField<'a> {
371 Pat(&'a ptr::P<ast::Pat>),
375 impl<'a> Rewrite for TuplePatField<'a> {
376 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
378 TuplePatField::Pat(p) => p.rewrite(context, shape),
379 TuplePatField::Dotdot(_) => Some("..".to_string()),
384 impl<'a> Spanned for TuplePatField<'a> {
385 fn span(&self) -> Span {
387 TuplePatField::Pat(p) => p.span(),
388 TuplePatField::Dotdot(span) => span,
393 impl<'a> TuplePatField<'a> {
394 fn is_dotdot(&self) -> bool {
396 TuplePatField::Pat(pat) => match pat.kind {
397 ast::PatKind::Rest => true,
400 TuplePatField::Dotdot(_) => true,
405 pub(crate) fn can_be_overflowed_pat(
406 context: &RewriteContext<'_>,
407 pat: &TuplePatField<'_>,
411 TuplePatField::Pat(pat) => match pat.kind {
412 ast::PatKind::Path(..)
413 | ast::PatKind::Tuple(..)
414 | ast::PatKind::Struct(..)
415 | ast::PatKind::TupleStruct(..) => context.use_block_indent() && len == 1,
416 ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => {
417 can_be_overflowed_pat(context, &TuplePatField::Pat(p), len)
419 ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
422 TuplePatField::Dotdot(..) => false,
426 fn rewrite_tuple_pat(
427 pats: &[ptr::P<ast::Pat>],
428 path_str: Option<String>,
430 context: &RewriteContext<'_>,
432 ) -> Option<String> {
433 let mut pat_vec: Vec<_> = pats.iter().map(|x| TuplePatField::Pat(x)).collect();
435 if pat_vec.is_empty() {
436 return Some(format!("{}()", path_str.unwrap_or_default()));
438 let wildcard_suffix_len = count_wildcard_suffix_len(context, &pat_vec, span, shape);
439 let (pat_vec, span) = if context.config.condense_wildcard_suffixes() && wildcard_suffix_len >= 2
441 let new_item_count = 1 + pat_vec.len() - wildcard_suffix_len;
442 let sp = pat_vec[new_item_count - 1].span();
443 let snippet = context.snippet(sp);
444 let lo = sp.lo() + BytePos(snippet.find_uncommented("_").unwrap() as u32);
445 pat_vec[new_item_count - 1] = TuplePatField::Dotdot(mk_sp(lo, lo + BytePos(1)));
447 &pat_vec[..new_item_count],
448 mk_sp(span.lo(), lo + BytePos(1)),
454 let is_last_pat_dotdot = pat_vec.last().map_or(false, |p| p.is_dotdot());
455 let add_comma = path_str.is_none() && pat_vec.len() == 1 && !is_last_pat_dotdot;
456 let path_str = path_str.unwrap_or_default();
458 overflow::rewrite_with_parens(
464 context.config.max_width(),
466 Some(SeparatorTactic::Always)
473 fn count_wildcard_suffix_len(
474 context: &RewriteContext<'_>,
475 patterns: &[TuplePatField<'_>],
479 let mut suffix_len = 0;
481 let items: Vec<_> = itemize_list(
482 context.snippet_provider,
486 |item| item.span().lo(),
487 |item| item.span().hi(),
488 |item| item.rewrite(context, shape),
489 context.snippet_provider.span_after(span, "("),
490 span.hi() - BytePos(1),
495 for item in items.iter().rev().take_while(|i| match i.item {
496 Some(ref internal_string) if internal_string == "_" => true,
501 if item.has_comment() {