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 rewrite::{Rewrite, RewriteContext};
13 use utils::{wrap_str, format_mutability, span_after};
14 use lists::{format_item_list, itemize_list};
15 use expr::{rewrite_unary_prefix, rewrite_pair, rewrite_tuple};
16 use types::rewrite_path;
18 use syntax::ast::{BindingMode, Pat, Pat_};
20 // FIXME(#18): implement pattern formatting.
21 impl Rewrite for Pat {
22 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
24 Pat_::PatBox(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, width, offset),
25 Pat_::PatIdent(binding_mode, ident, None) => {
26 let (prefix, mutability) = match binding_mode {
27 BindingMode::BindByRef(mutability) => ("ref ", mutability),
28 BindingMode::BindByValue(mutability) => ("", mutability),
30 let mut_infix = format_mutability(mutability);
31 let result = format!("{}{}{}", prefix, mut_infix, ident.node);
32 wrap_str(result, context.config.max_width, width, offset)
41 Pat_::PatQPath(ref q_self, ref path) => {
42 rewrite_path(context, true, Some(q_self), path, width, offset)
44 Pat_::PatRange(ref lhs, ref rhs) => {
45 rewrite_pair(&**lhs, &**rhs, "", "...", "", context, width, offset)
47 Pat_::PatRegion(ref pat, mutability) => {
48 let prefix = format!("&{}", format_mutability(mutability));
49 rewrite_unary_prefix(context, &prefix, &**pat, width, offset)
51 Pat_::PatTup(ref items) => {
52 rewrite_tuple(context,
53 items.iter().map(|x| &**x),
58 Pat_::PatEnum(ref path, Some(ref pat_vec)) => {
59 let path_str = try_opt!(::types::rewrite_path(context,
66 if pat_vec.is_empty() {
70 let width = try_opt!(width.checked_sub(path_str.len() + 1));
71 let offset = offset + path_str.len() + 1;
72 let items = itemize_list(context.codemap,
77 |item| item.rewrite(context, width, offset),
78 span_after(self.span, "(", context.codemap),
80 Some(format!("{}({})",
82 try_opt!(format_item_list(items, width, offset, context.config))))
85 Pat_::PatLit(ref expr) => expr.rewrite(context, width, offset),
86 // FIXME(#8): format remaining pattern variants.
87 Pat_::PatIdent(_, _, Some(..)) |
88 Pat_::PatEnum(_, None) |
92 wrap_str(context.snippet(self.span),
93 context.config.max_width,