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