]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
Unwrap match arms that are simple blocks
[rust.git] / src / chains.rs
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.
4 //
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.
10
11 // Formatting of chained expressions, i.e. expressions which are chained by
12 // dots: struct and enum field access and method calls.
13 //
14 // Instead of walking these subexpressions one-by-one, as is our usual strategy
15 // for expression formatting, we collect maximal sequences of these expressions
16 // and handle them simultaneously.
17 //
18 // Whenever possible, the entire chain is put on a single line. If that fails,
19 // we put each subexpression on a separate, much like the (default) function
20 // argument function argument strategy.
21
22 use Indent;
23 use rewrite::{Rewrite, RewriteContext};
24 use utils::first_line_width;
25 use expr::rewrite_call;
26 use config::BlockIndentStyle;
27
28 use syntax::{ast, ptr};
29 use syntax::codemap::{mk_sp, Span};
30 use syntax::print::pprust;
31
32 pub fn rewrite_chain(mut expr: &ast::Expr,
33                      context: &RewriteContext,
34                      width: usize,
35                      offset: Indent)
36                      -> Option<String> {
37     let total_span = expr.span;
38     let mut subexpr_list = vec![expr];
39
40     while let Some(subexpr) = pop_expr_chain(expr) {
41         subexpr_list.push(subexpr);
42         expr = subexpr;
43     }
44
45     let parent_block_indent = match context.config.chain_base_indent {
46         BlockIndentStyle::Visual => offset,
47         BlockIndentStyle::Inherit => context.block_indent,
48         BlockIndentStyle::Tabbed => context.block_indent.block_indent(context.config),
49     };
50     let parent_context = &RewriteContext { block_indent: parent_block_indent, ..*context };
51     let parent = subexpr_list.pop().unwrap();
52     let parent_rewrite = try_opt!(expr.rewrite(parent_context, width, offset));
53     let (indent, extend) = if !parent_rewrite.contains('\n') && is_continuable(parent) ||
54                               parent_rewrite.len() <= context.config.tab_spaces {
55         (offset + Indent::new(0, parent_rewrite.len()), true)
56     } else if is_block_expr(parent, &parent_rewrite) {
57         (parent_block_indent, false)
58     } else {
59         match context.config.chain_indent {
60             BlockIndentStyle::Inherit => (context.block_indent, false),
61             BlockIndentStyle::Tabbed => {
62                 (context.block_indent.block_indent(context.config), false)
63             }
64             BlockIndentStyle::Visual => {
65                 (offset + Indent::new(context.config.tab_spaces, 0), false)
66             }
67         }
68     };
69
70     let max_width = try_opt!((width + offset.width()).checked_sub(indent.width()));
71     let mut rewrites = try_opt!(subexpr_list.iter()
72                                             .rev()
73                                             .map(|e| {
74                                                 rewrite_chain_expr(e,
75                                                                    total_span,
76                                                                    context,
77                                                                    max_width,
78                                                                    indent)
79                                             })
80                                             .collect::<Option<Vec<_>>>());
81
82     // Total of all items excluding the last.
83     let almost_total = rewrites[..rewrites.len() - 1]
84                            .iter()
85                            .fold(0, |a, b| a + first_line_width(b)) +
86                        parent_rewrite.len();
87     let total_width = almost_total + first_line_width(rewrites.last().unwrap());
88     let veto_single_line = if context.config.take_source_hints && subexpr_list.len() > 1 {
89         // Look at the source code. Unless all chain elements start on the same
90         // line, we won't consider putting them on a single line either.
91         let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
92         let first_span = context.snippet(subexpr_list[1].span);
93         let last_iter = last_span.chars().take_while(|c| c.is_whitespace());
94
95         first_span.chars().chain(last_iter).any(|c| c == '\n')
96     } else {
97         false
98     };
99
100     let fits_single_line = !veto_single_line &&
101                            match subexpr_list[0].node {
102         ast::Expr_::ExprMethodCall(ref method_name, ref types, ref expressions)
103             if context.config.chains_overflow_last => {
104             let len = rewrites.len();
105             let (init, last) = rewrites.split_at_mut(len - 1);
106             let last = &mut last[0];
107
108             if init.iter().all(|s| !s.contains('\n')) && total_width <= width {
109                 let last_rewrite = width.checked_sub(almost_total)
110                                         .and_then(|inner_width| {
111                                             rewrite_method_call(method_name.node,
112                                                                 types,
113                                                                 expressions,
114                                                                 total_span,
115                                                                 context,
116                                                                 inner_width,
117                                                                 offset + almost_total)
118                                         });
119                 match last_rewrite {
120                     Some(mut string) => {
121                         ::std::mem::swap(&mut string, last);
122                         true
123                     }
124                     None => false,
125                 }
126             } else {
127                 false
128             }
129         }
130         _ => total_width <= width && rewrites.iter().all(|s| !s.contains('\n')),
131     };
132
133     let connector = if fits_single_line && !parent_rewrite.contains('\n') {
134         String::new()
135     } else {
136         format!("\n{}", indent.to_string(context.config))
137     };
138
139     let first_connector = if extend {
140         ""
141     } else {
142         &connector[..]
143     };
144
145     Some(format!("{}{}{}",
146                  parent_rewrite,
147                  first_connector,
148                  rewrites.join(&connector)))
149 }
150
151 // States whether an expression's last line exclusively consists of closing
152 // parens, braces and brackets in its idiomatic formatting.
153 fn is_block_expr(expr: &ast::Expr, repr: &str) -> bool {
154     match expr.node {
155         ast::Expr_::ExprStruct(..) |
156         ast::Expr_::ExprWhile(..) |
157         ast::Expr_::ExprWhileLet(..) |
158         ast::Expr_::ExprIf(..) |
159         ast::Expr_::ExprIfLet(..) |
160         ast::Expr_::ExprBlock(..) |
161         ast::Expr_::ExprLoop(..) |
162         ast::Expr_::ExprForLoop(..) |
163         ast::Expr_::ExprMatch(..) => repr.contains('\n'),
164         ast::Expr_::ExprParen(ref expr) |
165         ast::Expr_::ExprBinary(_, _, ref expr) |
166         ast::Expr_::ExprIndex(_, ref expr) |
167         ast::Expr_::ExprUnary(_, ref expr) => is_block_expr(expr, repr),
168         _ => false,
169     }
170 }
171
172 fn pop_expr_chain<'a>(expr: &'a ast::Expr) -> Option<&'a ast::Expr> {
173     match expr.node {
174         ast::Expr_::ExprMethodCall(_, _, ref expressions) => Some(&expressions[0]),
175         ast::Expr_::ExprTupField(ref subexpr, _) |
176         ast::Expr_::ExprField(ref subexpr, _) => Some(subexpr),
177         _ => None,
178     }
179 }
180
181 fn rewrite_chain_expr(expr: &ast::Expr,
182                       span: Span,
183                       context: &RewriteContext,
184                       width: usize,
185                       offset: Indent)
186                       -> Option<String> {
187     match expr.node {
188         ast::Expr_::ExprMethodCall(ref method_name, ref types, ref expressions) => {
189             let inner = &RewriteContext { block_indent: offset, ..*context };
190             rewrite_method_call(method_name.node,
191                                 types,
192                                 expressions,
193                                 span,
194                                 inner,
195                                 width,
196                                 offset)
197         }
198         ast::Expr_::ExprField(_, ref field) => Some(format!(".{}", field.node)),
199         ast::Expr_::ExprTupField(_, ref field) => Some(format!(".{}", field.node)),
200         _ => unreachable!(),
201     }
202 }
203
204 // Determines we can continue formatting a given expression on the same line.
205 fn is_continuable(expr: &ast::Expr) -> bool {
206     match expr.node {
207         ast::Expr_::ExprPath(..) => true,
208         _ => false,
209     }
210 }
211
212 fn rewrite_method_call(method_name: ast::Ident,
213                        types: &[ptr::P<ast::Ty>],
214                        args: &[ptr::P<ast::Expr>],
215                        span: Span,
216                        context: &RewriteContext,
217                        width: usize,
218                        offset: Indent)
219                        -> Option<String> {
220     let (lo, type_str) = if types.is_empty() {
221         (args[0].span.hi, String::new())
222     } else {
223         let type_list = types.iter().map(|ty| pprust::ty_to_string(ty)).collect::<Vec<_>>();
224
225         (types.last().unwrap().span.hi,
226          format!("::<{}>", type_list.join(", ")))
227     };
228
229     let callee_str = format!(".{}{}", method_name, type_str);
230     let span = mk_sp(lo, span.hi);
231
232     rewrite_call(context, &callee_str, &args[1..], span, width, offset)
233 }