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;
18 use expr::{can_be_overflowed_expr, rewrite_pair, rewrite_unary_prefix, wrap_struct_field,
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};
24 use rewrite::{Rewrite, RewriteContext};
27 use types::{rewrite_path, PathContext};
28 use utils::{format_mutability, mk_sp};
30 impl Rewrite for Pat {
31 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
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),
39 let mut_infix = format_mutability(mutability);
40 let id_str = ident.node.to_string();
41 let sub_pat = match *sub_pat {
46 .checked_sub(prefix.len() + mut_infix.len() + id_str.len() + 3)?;
49 p.rewrite(context, Shape::legacy(width, shape.indent))?
52 None => "".to_owned(),
55 Some(format!("{}{}{}{}", prefix, mut_infix, id_str, sub_pat))
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 => "..",
70 let infix = if context.config.spaces_around_ranges() {
71 format!(" {} ", infix)
78 PairParts::new("", &infix, ""),
81 SeparatorPlace::Front,
84 PatKind::Ref(ref pat, mutability) => {
85 let prefix = format!("&{}", format_mutability(mutability));
86 rewrite_unary_prefix(context, &prefix, &**pat, shape)
88 PatKind::Tuple(ref items, dotdot_pos) => {
89 rewrite_tuple_pat(items, dotdot_pos, None, self.span, context, shape)
91 PatKind::Path(ref q_self, ref path) => {
92 rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)
94 PatKind::TupleStruct(ref path, ref pat_vec, dotdot_pos) => {
95 let path_str = rewrite_path(context, PathContext::Expr, None, path, shape)?;
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
111 .map(|p| Some(format!("{}..", p.rewrite(context, shape)?)));
112 let suffix = suffix.iter().map(|p| p.rewrite(context, shape));
114 // Munge them together.
115 let pats: Option<Vec<String>> =
116 prefix.chain(slice_pat.into_iter()).chain(suffix).collect();
118 // Check that all the rewrites succeeded, and if not return None.
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(", "))
125 format!("[{}]", pats.join(", "))
129 PatKind::Struct(ref path, ref fields, ellipsis) => {
130 rewrite_struct_pat(path, fields, ellipsis, self.span, context, shape)
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)),
139 fn rewrite_struct_pat(
141 fields: &[codemap::Spanned<ast::FieldPat>],
144 context: &RewriteContext,
146 ) -> Option<String> {
148 let path_shape = shape.sub_width(2)?;
149 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
151 if fields.is_empty() && !ellipsis {
152 return Some(format!("{} {{}}", path_str));
155 let (ellipsis_str, terminator) = if ellipsis { (", ..", "..") } else { ("", "}") };
157 // 3 = ` { `, 2 = ` }`.
158 let (h_shape, v_shape) =
159 struct_lit_shape(shape, context, path_str.len() + 3, ellipsis_str.len() + 2)?;
161 let items = itemize_list(
162 context.snippet_provider,
168 |f| f.node.rewrite(context, v_shape),
169 context.snippet_provider.span_after(span, "{"),
173 let item_vec = items.collect::<Vec<_>>();
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);
179 let mut fields_str = write_list(&item_vec, &fmt)?;
180 let one_line_width = h_shape.map_or(0, |shape| shape.width);
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(",");
188 fields_str.push_str("\n");
189 fields_str.push_str(&nested_shape.indent.to_string(context.config));
190 fields_str.push_str("..");
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(" ");
198 fields_str.push_str(", ");
201 fields_str.push_str("..");
205 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
206 Some(format!("{} {{{}}}", path_str, fields_str))
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 {
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))
221 let nested_shape = shape.block_indent(context.config.tab_spaces());
222 let pat_str = self.pat.rewrite(context, nested_shape)?;
226 nested_shape.indent.to_string(context.config),
234 pub enum TuplePatField<'a> {
235 Pat(&'a ptr::P<ast::Pat>),
239 impl<'a> Rewrite for TuplePatField<'a> {
240 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
242 TuplePatField::Pat(p) => p.rewrite(context, shape),
243 TuplePatField::Dotdot(_) => Some("..".to_string()),
248 impl<'a> Spanned for TuplePatField<'a> {
249 fn span(&self) -> Span {
251 TuplePatField::Pat(p) => p.span(),
252 TuplePatField::Dotdot(span) => span,
257 pub fn can_be_overflowed_pat(context: &RewriteContext, pat: &TuplePatField, len: usize) -> bool {
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)
267 ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
270 TuplePatField::Dotdot(..) => false,
274 fn rewrite_tuple_pat(
275 pats: &[ptr::P<ast::Pat>],
276 dotdot_pos: Option<usize>,
277 path_str: Option<String>,
279 context: &RewriteContext,
281 ) -> Option<String> {
282 let mut pat_vec: Vec<_> = pats.into_iter().map(|x| TuplePatField::Pat(x)).collect();
284 if let Some(pos) = dotdot_pos {
285 let prev = if pos == 0 {
288 pats[pos - 1].span().hi()
290 let next = if pos + 1 >= pats.len() {
293 pats[pos + 1].span().lo()
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(
302 codemap::NO_EXPANSION,
304 pat_vec.insert(pos, dotdot);
307 if pat_vec.is_empty() {
308 return Some(format!("{}()", path_str.unwrap_or_default()));
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
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)));
320 &pat_vec[..new_item_count],
321 mk_sp(span.lo(), lo + BytePos(1)),
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;
333 let path_str = path_str.unwrap_or_default();
334 let mut pat_ref_vec = Vec::with_capacity(pat_vec.len());
336 pat_ref_vec.push(pat);
339 overflow::rewrite_with_parens(
345 context.config.max_width(),
347 Some(SeparatorTactic::Always)
354 fn count_wildcard_suffix_len(
355 context: &RewriteContext,
356 patterns: &[TuplePatField],
360 let mut suffix_len = 0;
362 let items: Vec<_> = itemize_list(
363 context.snippet_provider,
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),
375 for item in items.iter().rev().take_while(|i| match i.item {
376 Some(ref internal_string) if internal_string == "_" => true,
381 if item.pre_comment.is_some() || item.post_comment.is_some() {