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 codemap::SpanUtils;
13 use config::{IndentStyle, MultilineStyle};
14 use rewrite::{Rewrite, RewriteContext};
15 use utils::{wrap_str, format_mutability};
16 use lists::{DefinitiveListTactic, SeparatorTactic, format_item_list, itemize_list, ListItem,
17 struct_lit_shape, struct_lit_tactic, shape_for_tactic, struct_lit_formatting,
19 use expr::{rewrite_unary_prefix, rewrite_pair};
20 use types::{rewrite_path, PathContext};
22 use comment::FindUncommented;
24 use syntax::ast::{self, BindingMode, Pat, PatKind, FieldPat, RangeEnd};
26 use syntax::codemap::{self, BytePos, Span};
28 impl Rewrite for Pat {
29 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
31 PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, shape),
32 PatKind::Ident(binding_mode, ident, ref sub_pat) => {
33 let (prefix, mutability) = match binding_mode {
34 BindingMode::ByRef(mutability) => ("ref ", mutability),
35 BindingMode::ByValue(mutability) => ("", mutability),
37 let mut_infix = format_mutability(mutability);
38 let id_str = ident.node.to_string();
39 let sub_pat = match *sub_pat {
42 let width = try_opt!(shape
44 .checked_sub(prefix.len() + mut_infix.len() +
48 try_opt!(p.rewrite(context, Shape::legacy(width, shape.indent))))
50 None => "".to_owned(),
53 let result = format!("{}{}{}{}", prefix, mut_infix, id_str, sub_pat);
54 wrap_str(result, context.config.max_width(), shape)
63 PatKind::Range(ref lhs, ref rhs, ref end_kind) => {
65 RangeEnd::Included => {
66 rewrite_pair(&**lhs, &**rhs, "", "...", "", context, shape)
68 RangeEnd::Excluded => {
69 rewrite_pair(&**lhs, &**rhs, "", "..", "", context, shape)
73 PatKind::Ref(ref pat, mutability) => {
74 let prefix = format!("&{}", format_mutability(mutability));
75 rewrite_unary_prefix(context, &prefix, &**pat, shape)
77 PatKind::Tuple(ref items, dotdot_pos) => {
78 rewrite_tuple_pat(items, dotdot_pos, None, self.span, context, shape)
80 PatKind::Path(ref q_self, ref path) => {
81 rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)
83 PatKind::TupleStruct(ref path, ref pat_vec, dotdot_pos) => {
85 try_opt!(rewrite_path(context, PathContext::Expr, None, path, shape));
86 rewrite_tuple_pat(pat_vec,
93 PatKind::Lit(ref expr) => expr.rewrite(context, shape),
94 PatKind::Slice(ref prefix, ref slice_pat, ref suffix) => {
95 // Rewrite all the sub-patterns.
96 let prefix = prefix.iter().map(|p| p.rewrite(context, shape));
100 .map(|p| Some(format!("{}..", try_opt!(p.rewrite(context, shape)))));
101 let suffix = suffix.iter().map(|p| p.rewrite(context, shape));
103 // Munge them together.
104 let pats: Option<Vec<String>> =
105 prefix.chain(slice_pat.into_iter()).chain(suffix).collect();
107 // Check that all the rewrites succeeded, and if not return None.
108 let pats = try_opt!(pats);
110 // Unwrap all the sub-strings and join them with commas.
111 let result = if context.config.spaces_within_square_brackets() {
112 format!("[ {} ]", pats.join(", "))
114 format!("[{}]", pats.join(", "))
116 wrap_str(result, context.config.max_width(), shape)
118 PatKind::Struct(ref path, ref fields, elipses) => {
119 rewrite_struct_pat(path, fields, elipses, self.span, context, shape)
121 // FIXME(#819) format pattern macros.
122 PatKind::Mac(..) => {
123 wrap_str(context.snippet(self.span),
124 context.config.max_width(),
131 fn rewrite_struct_pat(path: &ast::Path,
132 fields: &[codemap::Spanned<ast::FieldPat>],
135 context: &RewriteContext,
139 let path_shape = try_opt!(shape.sub_width(2));
140 let path_str = try_opt!(rewrite_path(context, PathContext::Expr, None, path, path_shape));
142 if fields.len() == 0 && !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 try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, elipses_str.len() + 2));
152 let items = itemize_list(context.codemap,
157 |f| f.node.rewrite(context, v_shape),
158 context.codemap.span_after(span, "{"),
160 let item_vec = items.collect::<Vec<_>>();
162 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
163 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
164 let fmt = struct_lit_formatting(nested_shape, tactic, context, false);
166 let mut fields_str = try_opt!(write_list(&item_vec, &fmt));
169 if fields_str.contains('\n') {
170 // Add a missing trailing comma.
171 if fmt.trailing_separator == SeparatorTactic::Never {
172 fields_str.push_str(",");
174 fields_str.push_str("\n");
175 fields_str.push_str(&nested_shape.indent.to_string(context.config));
176 fields_str.push_str("..");
178 if !fields_str.is_empty() {
179 // there are preceeding struct fields being matched on
180 if fmt.tactic == DefinitiveListTactic::Vertical {
181 // if the tactic is Vertical, write_list already added a trailing ,
182 fields_str.push_str(" ");
184 fields_str.push_str(", ");
187 fields_str.push_str("..");
192 let fields_str = if context.config.struct_lit_style() == IndentStyle::Block &&
193 (fields_str.contains('\n') ||
194 context.config.struct_lit_multiline_style() ==
195 MultilineStyle::ForceMulti ||
196 fields_str.len() > h_shape.map(|s| s.width).unwrap_or(0)) {
197 format!("\n{}{}\n{}",
198 v_shape.indent.to_string(context.config),
200 shape.indent.to_string(context.config))
202 // One liner or visual indent.
203 format!(" {} ", fields_str)
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 {
215 wrap_str(format!("{}: {}", self.ident.to_string(), try_opt!(pat)),
216 context.config.max_width(),
222 enum TuplePatField<'a> {
223 Pat(&'a ptr::P<ast::Pat>),
227 impl<'a> Rewrite for TuplePatField<'a> {
228 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
230 TuplePatField::Pat(ref p) => p.rewrite(context, shape),
231 TuplePatField::Dotdot(_) => Some("..".to_string()),
236 impl<'a> Spanned for TuplePatField<'a> {
237 fn span(&self) -> Span {
239 TuplePatField::Pat(ref p) => p.span(),
240 TuplePatField::Dotdot(span) => span,
245 fn rewrite_tuple_pat(pats: &[ptr::P<ast::Pat>],
246 dotdot_pos: Option<usize>,
247 path_str: Option<String>,
249 context: &RewriteContext,
252 let mut pat_vec: Vec<_> = pats.into_iter().map(|x| TuplePatField::Pat(x)).collect();
254 if let Some(pos) = dotdot_pos {
255 let prev = if pos == 0 {
258 pats[pos - 1].span().hi
260 let next = if pos + 1 >= pats.len() {
263 pats[pos + 1].span().lo
265 let dot_span = codemap::mk_sp(prev, next);
266 let snippet = context.snippet(dot_span);
267 let lo = dot_span.lo + BytePos(snippet.find_uncommented("..").unwrap() as u32);
272 expn_id: codemap::NO_EXPANSION,
274 let dotdot = TuplePatField::Dotdot(span);
275 pat_vec.insert(pos, dotdot);
278 if pat_vec.is_empty() {
279 return Some(format!("{}()", try_opt!(path_str)));
281 // add comma if `(x,)`
282 let add_comma = path_str.is_none() && pat_vec.len() == 1 && dotdot_pos.is_none();
284 let path_len = path_str.as_ref().map(|p| p.len()).unwrap_or(0);
285 // 2 = "()".len(), 3 = "(,)".len()
286 let nested_shape = try_opt!(shape.sub_width(path_len + if add_comma { 3 } else { 2 }));
288 let nested_shape = nested_shape.visual_indent(path_len + 1);
289 let mut items: Vec<_> = itemize_list(context.codemap,
291 if add_comma { ",)" } else { ")" },
292 |item| item.span().lo,
293 |item| item.span().hi,
294 |item| item.rewrite(context, nested_shape),
295 context.codemap.span_after(span, "("),
296 span.hi - BytePos(1))
299 // Condense wildcard string suffix into a single ..
300 let wildcard_suffix_len = count_wildcard_suffix_len(&items);
302 let list = if context.config.condense_wildcard_suffices() && wildcard_suffix_len >= 2 {
303 let new_item_count = 1 + pats.len() - wildcard_suffix_len;
304 items[new_item_count - 1].item = Some("..".to_owned());
306 let da_iter = items.into_iter().take(new_item_count);
307 try_opt!(format_item_list(da_iter, nested_shape, context.config))
309 try_opt!(format_item_list(items.into_iter(), nested_shape, context.config))
314 Some(if context.config.spaces_within_parens() {
315 format!("{}( {} )", path_str, list)
317 format!("{}({})", path_str, list)
321 let comma = if add_comma { "," } else { "" };
322 Some(if context.config.spaces_within_parens() {
323 format!("( {}{} )", list, comma)
325 format!("({}{})", list, comma)
331 fn count_wildcard_suffix_len(items: &[ListItem]) -> usize {
332 let mut suffix_len = 0;
337 .take_while(|i| match i.item {
338 Some(ref internal_string) if internal_string == "_" => true,
343 if item.pre_comment.is_some() || item.post_comment.is_some() {