]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
Merge pull request #868 from rust-lang-nursery/tuple-wide
[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
31 pub fn rewrite_chain(mut expr: &ast::Expr,
32                      context: &RewriteContext,
33                      width: usize,
34                      offset: Indent)
35                      -> Option<String> {
36     let total_span = expr.span;
37     let mut subexpr_list = vec![expr];
38
39     while let Some(subexpr) = pop_expr_chain(expr) {
40         subexpr_list.push(subexpr);
41         expr = subexpr;
42     }
43
44     let parent_block_indent = match context.config.chain_base_indent {
45         BlockIndentStyle::Visual => offset,
46         BlockIndentStyle::Inherit => context.block_indent,
47         BlockIndentStyle::Tabbed => context.block_indent.block_indent(context.config),
48     };
49     let parent_context = &RewriteContext { block_indent: parent_block_indent, ..*context };
50     let parent = subexpr_list.pop().unwrap();
51     let parent_rewrite = try_opt!(expr.rewrite(parent_context, width, offset));
52     let (indent, extend) = if !parent_rewrite.contains('\n') && is_continuable(parent) ||
53                               parent_rewrite.len() <= context.config.tab_spaces {
54         (offset + Indent::new(0, parent_rewrite.len()), true)
55     } else if is_block_expr(parent, &parent_rewrite) {
56         (parent_block_indent, false)
57     } else {
58         match context.config.chain_indent {
59             BlockIndentStyle::Inherit => (context.block_indent, false),
60             BlockIndentStyle::Tabbed => (context.block_indent.block_indent(context.config), false),
61             BlockIndentStyle::Visual => (offset + Indent::new(context.config.tab_spaces, 0), false),
62         }
63     };
64
65     let max_width = try_opt!((width + offset.width()).checked_sub(indent.width()));
66     let mut rewrites = try_opt!(subexpr_list.iter()
67                                             .rev()
68                                             .map(|e| {
69                                                 rewrite_chain_expr(e,
70                                                                    total_span,
71                                                                    context,
72                                                                    max_width,
73                                                                    indent)
74                                             })
75                                             .collect::<Option<Vec<_>>>());
76
77     // Total of all items excluding the last.
78     let almost_total = rewrites[..rewrites.len() - 1]
79                            .iter()
80                            .fold(0, |a, b| a + first_line_width(b)) +
81                        parent_rewrite.len();
82     let total_width = almost_total + first_line_width(rewrites.last().unwrap());
83     let veto_single_line = if context.config.take_source_hints && subexpr_list.len() > 1 {
84         // Look at the source code. Unless all chain elements start on the same
85         // line, we won't consider putting them on a single line either.
86         let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
87         let first_span = context.snippet(subexpr_list[1].span);
88         let last_iter = last_span.chars().take_while(|c| c.is_whitespace());
89
90         first_span.chars().chain(last_iter).any(|c| c == '\n')
91     } else {
92         false
93     };
94
95     let fits_single_line = !veto_single_line &&
96                            match subexpr_list[0].node {
97         ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions)
98             if context.config.chains_overflow_last => {
99             let len = rewrites.len();
100             let (init, last) = rewrites.split_at_mut(len - 1);
101             let last = &mut last[0];
102
103             if init.iter().all(|s| !s.contains('\n')) && total_width <= width {
104                 let last_rewrite = width.checked_sub(almost_total)
105                                         .and_then(|inner_width| {
106                                             rewrite_method_call(method_name.node,
107                                                                 types,
108                                                                 expressions,
109                                                                 total_span,
110                                                                 context,
111                                                                 inner_width,
112                                                                 offset + almost_total)
113                                         });
114                 match last_rewrite {
115                     Some(mut string) => {
116                         ::std::mem::swap(&mut string, last);
117                         true
118                     }
119                     None => false,
120                 }
121             } else {
122                 false
123             }
124         }
125         _ => total_width <= width && rewrites.iter().all(|s| !s.contains('\n')),
126     };
127
128     let connector = if fits_single_line && !parent_rewrite.contains('\n') {
129         String::new()
130     } else {
131         format!("\n{}", indent.to_string(context.config))
132     };
133
134     let first_connector = if extend {
135         ""
136     } else {
137         &connector[..]
138     };
139
140     wrap_str(format!("{}{}{}",
141                      parent_rewrite,
142                      first_connector,
143                      rewrites.join(&connector)),
144              context.config.max_width,
145              width,
146              offset)
147 }
148
149 // States whether an expression's last line exclusively consists of closing
150 // parens, braces and brackets in its idiomatic formatting.
151 fn is_block_expr(expr: &ast::Expr, repr: &str) -> bool {
152     match expr.node {
153         ast::ExprKind::Struct(..) |
154         ast::ExprKind::While(..) |
155         ast::ExprKind::WhileLet(..) |
156         ast::ExprKind::If(..) |
157         ast::ExprKind::IfLet(..) |
158         ast::ExprKind::Block(..) |
159         ast::ExprKind::Loop(..) |
160         ast::ExprKind::ForLoop(..) |
161         ast::ExprKind::Match(..) => repr.contains('\n'),
162         ast::ExprKind::Paren(ref expr) |
163         ast::ExprKind::Binary(_, _, ref expr) |
164         ast::ExprKind::Index(_, ref expr) |
165         ast::ExprKind::Unary(_, ref expr) => is_block_expr(expr, repr),
166         _ => false,
167     }
168 }
169
170 fn pop_expr_chain(expr: &ast::Expr) -> Option<&ast::Expr> {
171     match expr.node {
172         ast::ExprKind::MethodCall(_, _, ref expressions) => Some(&expressions[0]),
173         ast::ExprKind::TupField(ref subexpr, _) |
174         ast::ExprKind::Field(ref subexpr, _) => Some(subexpr),
175         _ => None,
176     }
177 }
178
179 fn rewrite_chain_expr(expr: &ast::Expr,
180                       span: Span,
181                       context: &RewriteContext,
182                       width: usize,
183                       offset: Indent)
184                       -> Option<String> {
185     match expr.node {
186         ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) => {
187             let inner = &RewriteContext { block_indent: offset, ..*context };
188             rewrite_method_call(method_name.node,
189                                 types,
190                                 expressions,
191                                 span,
192                                 inner,
193                                 width,
194                                 offset)
195         }
196         ast::ExprKind::Field(_, ref field) => {
197             let s = format!(".{}", field.node);
198             if s.len() <= width {
199                 Some(s)
200             } else {
201                 None
202             }
203         }
204         ast::ExprKind::TupField(_, ref field) => {
205             let s = format!(".{}", field.node);
206             if s.len() <= width {
207                 Some(s)
208             } else {
209                 None
210             }
211         }
212         _ => unreachable!(),
213     }
214 }
215
216 // Determines we can continue formatting a given expression on the same line.
217 fn is_continuable(expr: &ast::Expr) -> bool {
218     match expr.node {
219         ast::ExprKind::Path(..) => true,
220         _ => false,
221     }
222 }
223
224 fn rewrite_method_call(method_name: ast::Ident,
225                        types: &[ptr::P<ast::Ty>],
226                        args: &[ptr::P<ast::Expr>],
227                        span: Span,
228                        context: &RewriteContext,
229                        width: usize,
230                        offset: Indent)
231                        -> Option<String> {
232     let (lo, type_str) = if types.is_empty() {
233         (args[0].span.hi, String::new())
234     } else {
235         let type_list: Vec<_> = try_opt!(types.iter()
236                                               .map(|ty| ty.rewrite(context, width, offset))
237                                               .collect());
238
239         (types.last().unwrap().span.hi, 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 }