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};
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 {
44 .checked_sub(prefix.len() + mut_infix.len() + id_str.len() + 3)
48 try_opt!(p.rewrite(context, Shape::legacy(width, shape.indent)))
51 None => "".to_owned(),
54 Some(format!("{}{}{}{}", prefix, mut_infix, id_str, sub_pat))
56 PatKind::Wild => if 1 <= shape.width {
61 PatKind::Range(ref lhs, ref rhs, ref end_kind) => match *end_kind {
62 RangeEnd::Included => rewrite_pair(
70 SeparatorPlace::Front,
72 RangeEnd::Excluded => rewrite_pair(
80 SeparatorPlace::Front,
83 PatKind::Ref(ref pat, mutability) => {
84 let prefix = format!("&{}", format_mutability(mutability));
85 rewrite_unary_prefix(context, &prefix, &**pat, shape)
87 PatKind::Tuple(ref items, dotdot_pos) => {
88 rewrite_tuple_pat(items, dotdot_pos, None, self.span, context, shape)
90 PatKind::Path(ref q_self, ref path) => {
91 rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)
93 PatKind::TupleStruct(ref path, ref pat_vec, dotdot_pos) => {
95 try_opt!(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.as_ref().map(|p| {
110 Some(format!("{}..", try_opt!(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.
119 let pats = try_opt!(pats);
121 // Unwrap all the sub-strings and join them with commas.
122 let result = if context.config.spaces_within_square_brackets() {
123 format!("[ {} ]", pats.join(", "))
125 format!("[{}]", pats.join(", "))
129 PatKind::Struct(ref path, ref fields, elipses) => {
130 rewrite_struct_pat(path, fields, elipses, self.span, context, shape)
132 // FIXME(#819) format pattern macros.
133 PatKind::Mac(..) => Some(context.snippet(self.span)),
138 fn rewrite_struct_pat(
140 fields: &[codemap::Spanned<ast::FieldPat>],
143 context: &RewriteContext,
145 ) -> Option<String> {
147 let path_shape = try_opt!(shape.sub_width(2));
148 let path_str = try_opt!(rewrite_path(
156 if fields.is_empty() && !elipses {
157 return Some(format!("{} {{}}", path_str));
160 let (elipses_str, terminator) = if elipses { (", ..", "..") } else { ("", "}") };
162 // 3 = ` { `, 2 = ` }`.
163 let (h_shape, v_shape) = try_opt!(struct_lit_shape(
167 elipses_str.len() + 2,
170 let items = itemize_list(
176 |f| f.node.rewrite(context, v_shape),
177 context.codemap.span_after(span, "{"),
181 let item_vec = items.collect::<Vec<_>>();
183 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
184 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
185 let fmt = struct_lit_formatting(nested_shape, tactic, context, false);
187 let mut fields_str = try_opt!(write_list(&item_vec, &fmt));
188 let one_line_width = h_shape.map_or(0, |shape| shape.width);
191 if fields_str.contains('\n') || fields_str.len() > one_line_width {
192 // Add a missing trailing comma.
193 if fmt.trailing_separator == SeparatorTactic::Never {
194 fields_str.push_str(",");
196 fields_str.push_str("\n");
197 fields_str.push_str(&nested_shape.indent.to_string(context.config));
198 fields_str.push_str("..");
200 if !fields_str.is_empty() {
201 // there are preceeding struct fields being matched on
202 if fmt.tactic == DefinitiveListTactic::Vertical {
203 // if the tactic is Vertical, write_list already added a trailing ,
204 fields_str.push_str(" ");
206 fields_str.push_str(", ");
209 fields_str.push_str("..");
213 let fields_str = wrap_struct_field(context, &fields_str, shape, v_shape, one_line_width);
214 Some(format!("{} {{{}}}", path_str, fields_str))
217 impl Rewrite for FieldPat {
218 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
219 let pat = self.pat.rewrite(context, shape);
220 if self.is_shorthand {
223 let pat_str = try_opt!(pat);
224 let id_str = self.ident.to_string();
225 let one_line_width = id_str.len() + 2 + pat_str.len();
226 if one_line_width <= shape.width {
227 Some(format!("{}: {}", id_str, pat_str))
229 let nested_shape = shape.block_indent(context.config.tab_spaces());
230 let pat_str = try_opt!(self.pat.rewrite(context, nested_shape));
234 nested_shape.indent.to_string(context.config),
242 pub enum TuplePatField<'a> {
243 Pat(&'a ptr::P<ast::Pat>),
247 impl<'a> Rewrite for TuplePatField<'a> {
248 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
250 TuplePatField::Pat(p) => p.rewrite(context, shape),
251 TuplePatField::Dotdot(_) => Some("..".to_string()),
256 impl<'a> Spanned for TuplePatField<'a> {
257 fn span(&self) -> Span {
259 TuplePatField::Pat(p) => p.span(),
260 TuplePatField::Dotdot(span) => span,
265 pub fn can_be_overflowed_pat(context: &RewriteContext, pat: &TuplePatField, len: usize) -> bool {
267 TuplePatField::Pat(pat) => match pat.node {
268 ast::PatKind::Path(..) | ast::PatKind::Tuple(..) | ast::PatKind::Struct(..) => {
269 context.use_block_indent() && len == 1
271 ast::PatKind::Ref(ref p, _) | ast::PatKind::Box(ref p) => {
272 can_be_overflowed_pat(context, &TuplePatField::Pat(p), len)
274 ast::PatKind::Lit(ref expr) => can_be_overflowed_expr(context, expr, len),
277 TuplePatField::Dotdot(..) => false,
281 fn rewrite_tuple_pat(
282 pats: &[ptr::P<ast::Pat>],
283 dotdot_pos: Option<usize>,
284 path_str: Option<String>,
286 context: &RewriteContext,
288 ) -> Option<String> {
289 let mut pat_vec: Vec<_> = pats.into_iter().map(|x| TuplePatField::Pat(x)).collect();
291 if let Some(pos) = dotdot_pos {
292 let prev = if pos == 0 {
295 pats[pos - 1].span().hi()
297 let next = if pos + 1 >= pats.len() {
300 pats[pos + 1].span().lo()
302 let dot_span = mk_sp(prev, next);
303 let snippet = context.snippet(dot_span);
304 let lo = dot_span.lo() + BytePos(snippet.find_uncommented("..").unwrap() as u32);
305 let dotdot = TuplePatField::Dotdot(Span::new(
309 codemap::NO_EXPANSION,
311 pat_vec.insert(pos, dotdot);
314 if pat_vec.is_empty() {
315 return Some(format!("{}()", path_str.unwrap_or_default()));
318 let wildcard_suffix_len = count_wildcard_suffix_len(context, &pat_vec, span, shape);
319 let (pat_vec, span) = if context.config.condense_wildcard_suffixes() && wildcard_suffix_len >= 2
321 let new_item_count = 1 + pat_vec.len() - wildcard_suffix_len;
322 let sp = pat_vec[new_item_count - 1].span();
323 let snippet = context.snippet(sp);
324 let lo = sp.lo() + BytePos(snippet.find_uncommented("_").unwrap() as u32);
325 pat_vec[new_item_count - 1] = TuplePatField::Dotdot(mk_sp(lo, lo + BytePos(1)));
327 &pat_vec[..new_item_count],
328 mk_sp(span.lo(), lo + BytePos(1)),
334 // add comma if `(x,)`
335 let add_comma = path_str.is_none() && pat_vec.len() == 1 && dotdot_pos.is_none();
336 let mut context = context.clone();
337 if let Some(&TuplePatField::Dotdot(..)) = pat_vec.last() {
338 context.inside_macro = true;
340 let path_str = path_str.unwrap_or_default();
341 let mut pat_ref_vec = Vec::with_capacity(pat_vec.len());
343 pat_ref_vec.push(pat);
357 fn count_wildcard_suffix_len(
358 context: &RewriteContext,
359 patterns: &[TuplePatField],
363 let mut suffix_len = 0;
365 let items: Vec<_> = itemize_list(
369 |item| item.span().lo(),
370 |item| item.span().hi(),
371 |item| item.rewrite(context, shape),
372 context.codemap.span_after(span, "("),
373 span.hi() - BytePos(1),
377 for item in items.iter().rev().take_while(|i| match i.item {
378 Some(ref internal_string) if internal_string == "_" => true,
383 if item.pre_comment.is_some() || item.post_comment.is_some() {