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.
11 use syntax::ast::{self, BindingMode, FieldPat, Pat, PatKind, RangeEnd, RangeSyntax};
12 use syntax::codemap::{self, BytePos, Span};
16 use codemap::SpanUtils;
17 use comment::FindUncommented;
18 use expr::{can_be_overflowed_expr, rewrite_call_inner, rewrite_pair, rewrite_unary_prefix,
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};
24 use types::{rewrite_path, PathContext};
25 use utils::{format_mutability, mk_sp};
27 impl Rewrite for Pat {
28 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
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),
36 let mut_infix = format_mutability(mutability);
37 let id_str = ident.node.to_string();
38 let sub_pat = match *sub_pat {
43 .checked_sub(prefix.len() + mut_infix.len() + id_str.len() + 3)?;
46 p.rewrite(context, Shape::legacy(width, shape.indent))?
49 None => "".to_owned(),
52 Some(format!("{}{}{}{}", prefix, mut_infix, id_str, sub_pat))
54 PatKind::Wild => if 1 <= shape.width {
59 PatKind::Range(ref lhs, ref rhs, ref end_kind) => {
60 let infix = match *end_kind {
61 RangeEnd::Included(RangeSyntax::DotDotDot) => "...",
62 RangeEnd::Included(RangeSyntax::DotDotEq) => "..=",
63 RangeEnd::Excluded => "..",
73 SeparatorPlace::Front,
76 PatKind::Ref(ref pat, mutability) => {
77 let prefix = format!("&{}", format_mutability(mutability));
78 rewrite_unary_prefix(context, &prefix, &**pat, shape)
80 PatKind::Tuple(ref items, dotdot_pos) => {
81 rewrite_tuple_pat(items, dotdot_pos, None, self.span, context, shape)
83 PatKind::Path(ref q_self, ref path) => {
84 rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)
86 PatKind::TupleStruct(ref path, ref pat_vec, dotdot_pos) => {
87 let path_str = rewrite_path(context, PathContext::Expr, None, path, shape)?;
97 PatKind::Lit(ref expr) => expr.rewrite(context, shape),
98 PatKind::Slice(ref prefix, ref slice_pat, ref suffix) => {
99 // Rewrite all the sub-patterns.
100 let prefix = prefix.iter().map(|p| p.rewrite(context, shape));
101 let slice_pat = slice_pat
103 .map(|p| Some(format!("{}..", p.rewrite(context, shape)?)));
104 let suffix = suffix.iter().map(|p| p.rewrite(context, shape));
106 // Munge them together.
107 let pats: Option<Vec<String>> =
108 prefix.chain(slice_pat.into_iter()).chain(suffix).collect();
110 // Check that all the rewrites succeeded, and if not return None.
113 // Unwrap all the sub-strings and join them with commas.
114 let result = if context.config.spaces_within_square_brackets() {
115 format!("[ {} ]", pats.join(", "))
117 format!("[{}]", pats.join(", "))
121 PatKind::Struct(ref path, ref fields, elipses) => {
122 rewrite_struct_pat(path, fields, elipses, self.span, context, shape)
124 // FIXME(#819) format pattern macros.
125 PatKind::Mac(..) => Some(context.snippet(self.span)),
130 fn rewrite_struct_pat(
132 fields: &[codemap::Spanned<ast::FieldPat>],
135 context: &RewriteContext,
137 ) -> Option<String> {
139 let path_shape = shape.sub_width(2)?;
140 let path_str = rewrite_path(context, PathContext::Expr, None, path, path_shape)?;
142 if fields.is_empty() && !elipses {
143 return Some(format!("{} {{}}", path_str));
146 let (elipses_str, terminator) = if elipses { (", ..", "..") } else { ("", "}") };
148 // 3 = ` { `, 2 = ` }`.
149 let (h_shape, v_shape) =
150 struct_lit_shape(shape, context, path_str.len() + 3, elipses_str.len() + 2)?;
152 let items = itemize_list(
158 |f| f.node.rewrite(context, v_shape),
159 context.codemap.span_after(span, "{"),
163 let item_vec = items.collect::<Vec<_>>();
165 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
166 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
167 let fmt = struct_lit_formatting(nested_shape, tactic, context, false);
169 let mut fields_str = write_list(&item_vec, &fmt)?;
170 let one_line_width = h_shape.map_or(0, |shape| shape.width);
173 if fields_str.contains('\n') || fields_str.len() > one_line_width {
174 // Add a missing trailing comma.
175 if fmt.trailing_separator == SeparatorTactic::Never {
176 fields_str.push_str(",");
178 fields_str.push_str("\n");
179 fields_str.push_str(&nested_shape.indent.to_string(context.config));
180 fields_str.push_str("..");
182 if !fields_str.is_empty() {
183 // there are preceeding struct fields being matched on
184 if fmt.tactic == DefinitiveListTactic::Vertical {
185 // if the tactic is Vertical, write_list already added a trailing ,
186 fields_str.push_str(" ");
188 fields_str.push_str(", ");
191 fields_str.push_str("..");
195 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
196 Some(format!("{} {{{}}}", path_str, fields_str))
199 impl Rewrite for FieldPat {
200 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
201 let pat = self.pat.rewrite(context, shape);
202 if self.is_shorthand {
206 let id_str = self.ident.to_string();
207 let one_line_width = id_str.len() + 2 + pat_str.len();
208 if one_line_width <= shape.width {
209 Some(format!("{}: {}", id_str, pat_str))
211 let nested_shape = shape.block_indent(context.config.tab_spaces());
212 let pat_str = self.pat.rewrite(context, nested_shape)?;
216 nested_shape.indent.to_string(context.config),
224 pub enum TuplePatField<'a> {
225 Pat(&'a ptr::P<ast::Pat>),
229 impl<'a> Rewrite for TuplePatField<'a> {
230 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
232 TuplePatField::Pat(p) => p.rewrite(context, shape),
233 TuplePatField::Dotdot(_) => Some("..".to_string()),
238 impl<'a> Spanned for TuplePatField<'a> {
239 fn span(&self) -> Span {
241 TuplePatField::Pat(p) => p.span(),
242 TuplePatField::Dotdot(span) => span,
247 pub fn can_be_overflowed_pat(context: &RewriteContext, pat: &TuplePatField, len: usize) -> bool {
249 TuplePatField::Pat(pat) => match pat.node {
250 ast::PatKind::Path(..) | ast::PatKind::Tuple(..) | ast::PatKind::Struct(..) => {
251 context.use_block_indent() && len == 1
253 ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => {
254 can_be_overflowed_pat(context, &TuplePatField::Pat(p), len)
256 ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
259 TuplePatField::Dotdot(..) => false,
263 fn rewrite_tuple_pat(
264 pats: &[ptr::P<ast::Pat>],
265 dotdot_pos: Option<usize>,
266 path_str: Option<String>,
268 context: &RewriteContext,
270 ) -> Option<String> {
271 let mut pat_vec: Vec<_> = pats.into_iter().map(|x| TuplePatField::Pat(x)).collect();
273 if let Some(pos) = dotdot_pos {
274 let prev = if pos == 0 {
277 pats[pos - 1].span().hi()
279 let next = if pos + 1 >= pats.len() {
282 pats[pos + 1].span().lo()
284 let dot_span = mk_sp(prev, next);
285 let snippet = context.snippet(dot_span);
286 let lo = dot_span.lo() + BytePos(snippet.find_uncommented("..").unwrap() as u32);
287 let dotdot = TuplePatField::Dotdot(Span::new(
291 codemap::NO_EXPANSION,
293 pat_vec.insert(pos, dotdot);
296 if pat_vec.is_empty() {
297 return Some(format!("{}()", path_str.unwrap_or_default()));
300 let wildcard_suffix_len = count_wildcard_suffix_len(context, &pat_vec, span, shape);
301 let (pat_vec, span) = if context.config.condense_wildcard_suffixes() && wildcard_suffix_len >= 2
303 let new_item_count = 1 + pat_vec.len() - wildcard_suffix_len;
304 let sp = pat_vec[new_item_count - 1].span();
305 let snippet = context.snippet(sp);
306 let lo = sp.lo() + BytePos(snippet.find_uncommented("_").unwrap() as u32);
307 pat_vec[new_item_count - 1] = TuplePatField::Dotdot(mk_sp(lo, lo + BytePos(1)));
309 &pat_vec[..new_item_count],
310 mk_sp(span.lo(), lo + BytePos(1)),
316 // add comma if `(x,)`
317 let add_comma = path_str.is_none() && pat_vec.len() == 1 && dotdot_pos.is_none();
318 let mut context = context.clone();
319 if let Some(&TuplePatField::Dotdot(..)) = pat_vec.last() {
320 context.inside_macro = true;
322 let path_str = path_str.unwrap_or_default();
323 let mut pat_ref_vec = Vec::with_capacity(pat_vec.len());
325 pat_ref_vec.push(pat);
339 fn count_wildcard_suffix_len(
340 context: &RewriteContext,
341 patterns: &[TuplePatField],
345 let mut suffix_len = 0;
347 let items: Vec<_> = itemize_list(
351 |item| item.span().lo(),
352 |item| item.span().hi(),
353 |item| item.rewrite(context, shape),
354 context.codemap.span_after(span, "("),
355 span.hi() - BytePos(1),
359 for item in items.iter().rev().take_while(|i| match i.item {
360 Some(ref internal_string) if internal_string == "_" => true,
365 if item.pre_comment.is_some() || item.post_comment.is_some() {