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.width.checked_sub(prefix.len() +
47 try_opt!(p.rewrite(context, Shape::legacy(width, shape.indent))))
49 None => "".to_owned(),
52 let result = format!("{}{}{}{}", prefix, mut_infix, id_str, sub_pat);
53 wrap_str(result, context.config.max_width, shape)
62 PatKind::Range(ref lhs, ref rhs, ref end_kind) => {
64 RangeEnd::Included => {
65 rewrite_pair(&**lhs, &**rhs, "", "...", "", context, shape)
67 RangeEnd::Excluded => {
68 rewrite_pair(&**lhs, &**rhs, "", "..", "", context, shape)
72 PatKind::Ref(ref pat, mutability) => {
73 let prefix = format!("&{}", format_mutability(mutability));
74 rewrite_unary_prefix(context, &prefix, &**pat, shape)
76 PatKind::Tuple(ref items, dotdot_pos) => {
77 rewrite_tuple_pat(items, dotdot_pos, None, self.span, context, shape)
79 PatKind::Path(ref q_self, ref path) => {
80 rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)
82 PatKind::TupleStruct(ref path, ref pat_vec, dotdot_pos) => {
84 try_opt!(rewrite_path(context, PathContext::Expr, None, path, shape));
85 rewrite_tuple_pat(pat_vec,
92 PatKind::Lit(ref expr) => expr.rewrite(context, shape),
93 PatKind::Slice(ref prefix, ref slice_pat, ref suffix) => {
94 // Rewrite all the sub-patterns.
95 let prefix = prefix.iter().map(|p| p.rewrite(context, shape));
99 .map(|p| Some(format!("{}..", try_opt!(p.rewrite(context, shape)))));
100 let suffix = suffix.iter().map(|p| p.rewrite(context, shape));
102 // Munge them together.
103 let pats: Option<Vec<String>> =
104 prefix.chain(slice_pat.into_iter()).chain(suffix).collect();
106 // Check that all the rewrites succeeded, and if not return None.
107 let pats = try_opt!(pats);
109 // Unwrap all the sub-strings and join them with commas.
110 let result = if context.config.spaces_within_square_brackets {
111 format!("[ {} ]", pats.join(", "))
113 format!("[{}]", pats.join(", "))
115 wrap_str(result, context.config.max_width, shape)
117 PatKind::Struct(ref path, ref fields, elipses) => {
118 rewrite_struct_pat(path, fields, elipses, self.span, context, shape)
120 // FIXME(#819) format pattern macros.
121 PatKind::Mac(..) => {
122 wrap_str(context.snippet(self.span), context.config.max_width, shape)
128 fn rewrite_struct_pat(path: &ast::Path,
129 fields: &[codemap::Spanned<ast::FieldPat>],
132 context: &RewriteContext,
136 let path_shape = try_opt!(shape.sub_width(2));
137 let path_str = try_opt!(rewrite_path(context, PathContext::Expr, None, path, path_shape));
139 if fields.len() == 0 && !elipses {
140 return Some(format!("{} {{}}", path_str));
143 let (elipses_str, terminator) = if elipses { (", ..", "..") } else { ("", "}") };
145 // 3 = ` { `, 2 = ` }`.
146 let (h_shape, v_shape) =
147 try_opt!(struct_lit_shape(shape, context, path_str.len() + 3, elipses_str.len() + 2));
149 let items = itemize_list(context.codemap,
154 |f| f.node.rewrite(context, v_shape),
155 context.codemap.span_after(span, "{"),
157 let item_vec = items.collect::<Vec<_>>();
159 let tactic = struct_lit_tactic(h_shape, context, &item_vec);
160 let nested_shape = shape_for_tactic(tactic, h_shape, v_shape);
161 let fmt = struct_lit_formatting(nested_shape, tactic, context, false);
163 let mut fields_str = try_opt!(write_list(&item_vec, &fmt));
166 if fields_str.contains('\n') {
167 // Add a missing trailing comma.
168 if fmt.trailing_separator == SeparatorTactic::Never {
169 fields_str.push_str(",");
171 fields_str.push_str("\n");
172 fields_str.push_str(&nested_shape.indent.to_string(context.config));
173 fields_str.push_str("..");
175 if !fields_str.is_empty() {
176 // there are preceeding struct fields being matched on
177 if fmt.tactic == DefinitiveListTactic::Vertical {
178 // if the tactic is Vertical, write_list already added a trailing ,
179 fields_str.push_str(" ");
181 fields_str.push_str(", ");
184 fields_str.push_str("..");
189 let fields_str = if context.config.struct_lit_style == IndentStyle::Block &&
190 (fields_str.contains('\n') ||
191 context.config.struct_lit_multiline_style == MultilineStyle::ForceMulti ||
192 fields_str.len() > h_shape.map(|s| s.width).unwrap_or(0)) {
193 format!("\n{}{}\n{}",
194 v_shape.indent.to_string(context.config),
196 shape.indent.to_string(context.config))
198 // One liner or visual indent.
199 format!(" {} ", fields_str)
202 Some(format!("{} {{{}}}", path_str, fields_str))
205 impl Rewrite for FieldPat {
206 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
207 let pat = self.pat.rewrite(context, shape);
208 if self.is_shorthand {
211 wrap_str(format!("{}: {}", self.ident.to_string(), try_opt!(pat)),
212 context.config.max_width,
218 enum TuplePatField<'a> {
219 Pat(&'a ptr::P<ast::Pat>),
223 impl<'a> Rewrite for TuplePatField<'a> {
224 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
226 TuplePatField::Pat(ref p) => p.rewrite(context, shape),
227 TuplePatField::Dotdot(_) => Some("..".to_string()),
232 impl<'a> Spanned for TuplePatField<'a> {
233 fn span(&self) -> Span {
235 TuplePatField::Pat(ref p) => p.span(),
236 TuplePatField::Dotdot(span) => span,
241 fn rewrite_tuple_pat(pats: &[ptr::P<ast::Pat>],
242 dotdot_pos: Option<usize>,
243 path_str: Option<String>,
245 context: &RewriteContext,
248 let mut pat_vec: Vec<_> = pats.into_iter().map(|x| TuplePatField::Pat(x)).collect();
250 if let Some(pos) = dotdot_pos {
251 let prev = if pos == 0 {
254 pats[pos - 1].span().hi
256 let next = if pos + 1 >= pats.len() {
259 pats[pos + 1].span().lo
261 let dot_span = codemap::mk_sp(prev, next);
262 let snippet = context.snippet(dot_span);
263 let lo = dot_span.lo + BytePos(snippet.find_uncommented("..").unwrap() as u32);
268 expn_id: codemap::NO_EXPANSION,
270 let dotdot = TuplePatField::Dotdot(span);
271 pat_vec.insert(pos, dotdot);
274 if pat_vec.is_empty() {
275 return Some(format!("{}()", try_opt!(path_str)));
277 // add comma if `(x,)`
278 let add_comma = path_str.is_none() && pat_vec.len() == 1 && dotdot_pos.is_none();
280 let path_len = path_str.as_ref().map(|p| p.len()).unwrap_or(0);
281 // 2 = "()".len(), 3 = "(,)".len()
282 let nested_shape = try_opt!(shape.sub_width(path_len + if add_comma { 3 } else { 2 }));
284 let nested_shape = nested_shape.visual_indent(path_len + 1);
285 let mut items: Vec<_> = itemize_list(context.codemap,
287 if add_comma { ",)" } else { ")" },
288 |item| item.span().lo,
289 |item| item.span().hi,
290 |item| item.rewrite(context, nested_shape),
291 context.codemap.span_after(span, "("),
292 span.hi - BytePos(1))
295 // Condense wildcard string suffix into a single ..
296 let wildcard_suffix_len = count_wildcard_suffix_len(&items);
298 let list = if context.config.condense_wildcard_suffixes && wildcard_suffix_len >= 2 {
299 let new_item_count = 1 + pats.len() - wildcard_suffix_len;
300 items[new_item_count - 1].item = Some("..".to_owned());
302 let da_iter = items.into_iter().take(new_item_count);
303 try_opt!(format_item_list(da_iter, nested_shape, context.config))
305 try_opt!(format_item_list(items.into_iter(), nested_shape, context.config))
310 Some(if context.config.spaces_within_parens {
311 format!("{}( {} )", path_str, list)
313 format!("{}({})", path_str, list)
317 let comma = if add_comma { "," } else { "" };
318 Some(if context.config.spaces_within_parens {
319 format!("( {}{} )", list, comma)
321 format!("({}{})", list, comma)
327 fn count_wildcard_suffix_len(items: &[ListItem]) -> usize {
328 let mut suffix_len = 0;
330 for item in items.iter().rev().take_while(|i| match i.item {
331 Some(ref internal_string) if internal_string ==
337 if item.pre_comment.is_some() || item.post_comment.is_some() {