]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
Merge pull request #615 from JanLikar/version
[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::{wrap_str, 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 => (context.block_indent.block_indent(context.config), false),
62             BlockIndentStyle::Visual => (offset + Indent::new(context.config.tab_spaces, 0), false),
63         }
64     };
65
66     let max_width = try_opt!((width + offset.width()).checked_sub(indent.width()));
67     let mut rewrites = try_opt!(subexpr_list.iter()
68                                             .rev()
69                                             .map(|e| {
70                                                 rewrite_chain_expr(e,
71                                                                    total_span,
72                                                                    context,
73                                                                    max_width,
74                                                                    indent)
75                                             })
76                                             .collect::<Option<Vec<_>>>());
77
78     // Total of all items excluding the last.
79     let almost_total = rewrites[..rewrites.len() - 1]
80                            .iter()
81                            .fold(0, |a, b| a + first_line_width(b)) +
82                        parent_rewrite.len();
83     let total_width = almost_total + first_line_width(rewrites.last().unwrap());
84     let veto_single_line = if context.config.take_source_hints && subexpr_list.len() > 1 {
85         // Look at the source code. Unless all chain elements start on the same
86         // line, we won't consider putting them on a single line either.
87         let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
88         let first_span = context.snippet(subexpr_list[1].span);
89         let last_iter = last_span.chars().take_while(|c| c.is_whitespace());
90
91         first_span.chars().chain(last_iter).any(|c| c == '\n')
92     } else {
93         false
94     };
95
96     let fits_single_line = !veto_single_line &&
97                            match subexpr_list[0].node {
98         ast::Expr_::ExprMethodCall(ref method_name, ref types, ref expressions)
99             if context.config.chains_overflow_last => {
100             let len = rewrites.len();
101             let (init, last) = rewrites.split_at_mut(len - 1);
102             let last = &mut last[0];
103
104             if init.iter().all(|s| !s.contains('\n')) && total_width <= width {
105                 let last_rewrite = width.checked_sub(almost_total)
106                                         .and_then(|inner_width| {
107                                             rewrite_method_call(method_name.node,
108                                                                 types,
109                                                                 expressions,
110                                                                 total_span,
111                                                                 context,
112                                                                 inner_width,
113                                                                 offset + almost_total)
114                                         });
115                 match last_rewrite {
116                     Some(mut string) => {
117                         ::std::mem::swap(&mut string, last);
118                         true
119                     }
120                     None => false,
121                 }
122             } else {
123                 false
124             }
125         }
126         _ => total_width <= width && rewrites.iter().all(|s| !s.contains('\n')),
127     };
128
129     let connector = if fits_single_line && !parent_rewrite.contains('\n') {
130         String::new()
131     } else {
132         format!("\n{}", indent.to_string(context.config))
133     };
134
135     let first_connector = if extend {
136         ""
137     } else {
138         &connector[..]
139     };
140
141     wrap_str(format!("{}{}{}",
142                      parent_rewrite,
143                      first_connector,
144                      rewrites.join(&connector)),
145              context.config.max_width,
146              width,
147              offset)
148 }
149
150 // States whether an expression's last line exclusively consists of closing
151 // parens, braces and brackets in its idiomatic formatting.
152 fn is_block_expr(expr: &ast::Expr, repr: &str) -> bool {
153     match expr.node {
154         ast::Expr_::ExprStruct(..) |
155         ast::Expr_::ExprWhile(..) |
156         ast::Expr_::ExprWhileLet(..) |
157         ast::Expr_::ExprIf(..) |
158         ast::Expr_::ExprIfLet(..) |
159         ast::Expr_::ExprBlock(..) |
160         ast::Expr_::ExprLoop(..) |
161         ast::Expr_::ExprForLoop(..) |
162         ast::Expr_::ExprMatch(..) => repr.contains('\n'),
163         ast::Expr_::ExprParen(ref expr) |
164         ast::Expr_::ExprBinary(_, _, ref expr) |
165         ast::Expr_::ExprIndex(_, ref expr) |
166         ast::Expr_::ExprUnary(_, ref expr) => is_block_expr(expr, repr),
167         _ => false,
168     }
169 }
170
171 fn pop_expr_chain(expr: &ast::Expr) -> Option<&ast::Expr> {
172     match expr.node {
173         ast::Expr_::ExprMethodCall(_, _, ref expressions) => Some(&expressions[0]),
174         ast::Expr_::ExprTupField(ref subexpr, _) |
175         ast::Expr_::ExprField(ref subexpr, _) => Some(subexpr),
176         _ => None,
177     }
178 }
179
180 fn rewrite_chain_expr(expr: &ast::Expr,
181                       span: Span,
182                       context: &RewriteContext,
183                       width: usize,
184                       offset: Indent)
185                       -> Option<String> {
186     match expr.node {
187         ast::Expr_::ExprMethodCall(ref method_name, ref types, ref expressions) => {
188             let inner = &RewriteContext { block_indent: offset, ..*context };
189             rewrite_method_call(method_name.node,
190                                 types,
191                                 expressions,
192                                 span,
193                                 inner,
194                                 width,
195                                 offset)
196         }
197         ast::Expr_::ExprField(_, ref field) => {
198             let s = format!(".{}", field.node);
199             if s.len() <= width {
200                 Some(s)
201             } else {
202                 None
203             }
204         }
205         ast::Expr_::ExprTupField(_, ref field) => {
206             let s = format!(".{}", field.node);
207             if s.len() <= width {
208                 Some(s)
209             } else {
210                 None
211             }
212         }
213         _ => unreachable!(),
214     }
215 }
216
217 // Determines we can continue formatting a given expression on the same line.
218 fn is_continuable(expr: &ast::Expr) -> bool {
219     match expr.node {
220         ast::Expr_::ExprPath(..) => true,
221         _ => false,
222     }
223 }
224
225 fn rewrite_method_call(method_name: ast::Ident,
226                        types: &[ptr::P<ast::Ty>],
227                        args: &[ptr::P<ast::Expr>],
228                        span: Span,
229                        context: &RewriteContext,
230                        width: usize,
231                        offset: Indent)
232                        -> Option<String> {
233     let (lo, type_str) = if types.is_empty() {
234         (args[0].span.hi, String::new())
235     } else {
236         let type_list = types.iter().map(|ty| pprust::ty_to_string(ty)).collect::<Vec<_>>();
237
238         (types.last().unwrap().span.hi,
239          format!("::<{}>", type_list.join(", ")))
240     };
241
242     let callee_str = format!(".{}{}", method_name, type_str);
243     let span = mk_sp(lo, span.hi);
244
245     rewrite_call(context, &callee_str, &args[1..], span, width, offset)
246 }