]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
Tests
[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 /// Depends on config options: `chain_base_indent` is the indent to use for
23 /// blocks in the parent/root/base of the chain.
24 /// E.g., `let foo = { aaaa; bbb; ccc }.bar.baz();`, we would layout for the
25 /// following values of `chain_base_indent`:
26 /// Visual:
27 /// ```
28 /// let foo = {
29 ///               aaaa;
30 ///               bbb;
31 ///               ccc
32 ///           }
33 ///           .bar
34 ///           .baz();
35 /// ```
36 /// Inherit:
37 /// ```
38 /// let foo = {
39 ///     aaaa;
40 ///     bbb;
41 ///     ccc
42 /// }
43 /// .bar
44 /// .baz();
45 /// ```
46 /// Tabbed:
47 /// ```
48 /// let foo = {
49 ///         aaaa;
50 ///         bbb;
51 ///         ccc
52 ///     }
53 ///     .bar
54 ///     .baz();
55 /// ```
56 ///
57 /// `chain_indent` dictates how the rest of the chain is aligned. This only seems
58 /// to have an effect if the first non-root part of the chain is put on a
59 /// newline, otherwise we align the dots:
60 /// ```
61 /// foo.bar
62 ///    .baz()
63 /// ```
64 /// If the first item in the chain is a block expression, we align the dots with
65 /// the braces.
66 ///
67 /// Otherwise:
68 /// Visual:
69 /// ```
70 /// let a = foo(aaa, bbb)
71 ///             .bar
72 ///             .baz()
73 /// ```
74 /// Visual seems to be a tab indented from the indent of the whole expression.
75 /// Inherit:
76 /// ```
77 /// let a = foo(aaa, bbb)
78 /// .bar
79 /// .baz()
80 /// ```
81 /// Tabbed:
82 /// ```
83 /// let a = foo(aaa, bbb)
84 ///     .bar
85 ///     .baz()
86 /// ```
87 /// `chains_overflow_last` applies only to chains where the last item is a
88 /// method call. Usually, any line break in a chain sub-expression causes the
89 /// whole chain to be split with newlines at each `.`. With `chains_overflow_last`
90 /// true, then we allow the last method call to spill over multiple lines without
91 /// forcing the rest of the chain to be split.
92
93
94 use Indent;
95 use rewrite::{Rewrite, RewriteContext};
96 use utils::{wrap_str, first_line_width};
97 use expr::rewrite_call;
98 use config::BlockIndentStyle;
99
100 use syntax::{ast, ptr};
101 use syntax::codemap::{mk_sp, Span};
102
103
104 pub fn rewrite_chain(expr: &ast::Expr,
105                      context: &RewriteContext,
106                      width: usize,
107                      offset: Indent)
108                      -> Option<String> {
109     let total_span = expr.span;
110     let (parent, subexpr_list) = make_subexpr_list(expr);
111
112     // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
113     let parent_block_indent = chain_base_indent(context, offset);
114     let parent_context = &RewriteContext { block_indent: parent_block_indent, ..*context };
115     let parent_rewrite = try_opt!(parent.rewrite(parent_context, width, offset));
116
117     // Decide how to layout the rest of the chain. `extend` is true if we can
118     // put the first non-parent item on the same line as the parent.
119     let (indent, extend) = if !parent_rewrite.contains('\n') && is_continuable(parent) ||
120                               parent_rewrite.len() <= context.config.tab_spaces {
121         // Try and put at least the first two items on the same line.
122         (chain_indent(context, offset + Indent::new(0, parent_rewrite.len())), true)
123     } else if is_block_expr(parent, &parent_rewrite) {
124         // The parent is a block, so align the rest of the chain with the closing
125         // brace.
126         (parent_block_indent, false)
127     } else if parent_rewrite.contains('\n') {
128         (chain_indent(context, parent_block_indent.block_indent(context.config)), false)
129     } else {
130         (hacked_chain_indent(context, offset + Indent::new(0, parent_rewrite.len())), false)
131     };
132
133     let max_width = try_opt!((width + offset.width()).checked_sub(indent.width()));
134     let mut rewrites = try_opt!(subexpr_list.iter()
135                                             .rev()
136                                             .map(|e| {
137                                                 rewrite_chain_subexpr(e,
138                                                                       total_span,
139                                                                       context,
140                                                                       max_width,
141                                                                       indent)
142                                             })
143                                             .collect::<Option<Vec<_>>>());
144
145     // Total of all items excluding the last.
146     let almost_total = rewrites[..rewrites.len() - 1]
147         .iter()
148         .fold(0, |a, b| a + first_line_width(b)) + parent_rewrite.len();
149     let total_width = almost_total + first_line_width(rewrites.last().unwrap());
150
151     let veto_single_line = if context.config.take_source_hints && subexpr_list.len() > 1 {
152         // Look at the source code. Unless all chain elements start on the same
153         // line, we won't consider putting them on a single line either.
154         let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
155         let first_span = context.snippet(subexpr_list[1].span);
156         let last_iter = last_span.chars().take_while(|c| c.is_whitespace());
157
158         first_span.chars().chain(last_iter).any(|c| c == '\n')
159     } else {
160         false
161     };
162
163     let mut fits_single_line = !veto_single_line && total_width <= width;
164     if fits_single_line {
165         let len = rewrites.len();
166         let (init, last) = rewrites.split_at_mut(len - 1);
167         fits_single_line = init.iter().all(|s| !s.contains('\n'));
168
169         if fits_single_line {
170             fits_single_line = match expr.node {
171                 ref e @ ast::ExprKind::MethodCall(..) if context.config.chains_overflow_last => {
172                     rewrite_method_call_with_overflow(e,
173                                                       &mut last[0],
174                                                       almost_total,
175                                                       width,
176                                                       total_span,
177                                                       context,
178                                                       offset)
179                 }
180                 _ => !last[0].contains('\n'),
181             }
182         }
183     }
184
185     let connector = if fits_single_line && !parent_rewrite.contains('\n') {
186         // Yay, we can put everything on one line.
187         String::new()
188     } else {
189         // Use new lines.
190         format!("\n{}", indent.to_string(context.config))
191     };
192
193     let first_connector = if extend {
194         ""
195     } else {
196         &connector
197     };
198
199     wrap_str(format!("{}{}{}",
200                      parent_rewrite,
201                      first_connector,
202                      rewrites.join(&connector)),
203              context.config.max_width,
204              width,
205              offset)
206 }
207
208 // States whether an expression's last line exclusively consists of closing
209 // parens, braces, and brackets in its idiomatic formatting.
210 fn is_block_expr(expr: &ast::Expr, repr: &str) -> bool {
211     match expr.node {
212         ast::ExprKind::Struct(..) |
213         ast::ExprKind::While(..) |
214         ast::ExprKind::WhileLet(..) |
215         ast::ExprKind::If(..) |
216         ast::ExprKind::IfLet(..) |
217         ast::ExprKind::Block(..) |
218         ast::ExprKind::Loop(..) |
219         ast::ExprKind::ForLoop(..) |
220         ast::ExprKind::Match(..) => repr.contains('\n'),
221         ast::ExprKind::Paren(ref expr) |
222         ast::ExprKind::Binary(_, _, ref expr) |
223         ast::ExprKind::Index(_, ref expr) |
224         ast::ExprKind::Unary(_, ref expr) => is_block_expr(expr, repr),
225         _ => false,
226     }
227 }
228
229 // Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
230 // E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
231 fn make_subexpr_list(mut expr: &ast::Expr) -> (&ast::Expr, Vec<&ast::Expr>) {
232     fn pop_expr_chain(expr: &ast::Expr) -> Option<&ast::Expr> {
233         match expr.node {
234             ast::ExprKind::MethodCall(_, _, ref expressions) => Some(&expressions[0]),
235             ast::ExprKind::TupField(ref subexpr, _) |
236             ast::ExprKind::Field(ref subexpr, _) => Some(subexpr),
237             _ => None,
238         }
239     }
240
241     let mut subexpr_list = vec![expr];
242
243     while let Some(subexpr) = pop_expr_chain(expr) {
244         subexpr_list.push(subexpr);
245         expr = subexpr;
246     }
247
248     let parent = subexpr_list.pop().unwrap();
249     (parent, subexpr_list)
250 }
251
252 fn chain_base_indent(context: &RewriteContext, offset: Indent) -> Indent {
253     match context.config.chain_base_indent {
254         BlockIndentStyle::Visual => offset,
255         BlockIndentStyle::Inherit => context.block_indent,
256         BlockIndentStyle::Tabbed => context.block_indent.block_indent(context.config),
257     }
258 }
259
260 fn chain_indent(context: &RewriteContext, offset: Indent) -> Indent {
261     match context.config.chain_indent {
262         BlockIndentStyle::Visual => offset,
263         BlockIndentStyle::Inherit => context.block_indent,
264         BlockIndentStyle::Tabbed => context.block_indent.block_indent(context.config),
265     }
266 }
267
268 // Temporary hack - ignores visual indenting because this function should be
269 // called where it is not possible to use visual indentation.
270 fn hacked_chain_indent(context: &RewriteContext, _offset: Indent) -> Indent {
271     match context.config.chain_indent {
272         BlockIndentStyle::Inherit => context.block_indent,
273         BlockIndentStyle::Visual | BlockIndentStyle::Tabbed => {
274             context.block_indent.block_indent(context.config)
275         }
276     }
277 }
278
279 fn rewrite_method_call_with_overflow(expr_kind: &ast::ExprKind,
280                                      last: &mut String,
281                                      almost_total: usize,
282                                      width: usize,
283                                      total_span: Span,
284                                      context: &RewriteContext,
285                                      offset: Indent)
286                                      -> bool {
287     if let &ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) = expr_kind {
288         let budget = match width.checked_sub(almost_total) {
289             Some(b) => b,
290             None => return false,
291         };
292         let mut last_rewrite = rewrite_method_call(method_name.node,
293                                                    types,
294                                                    expressions,
295                                                    total_span,
296                                                    context,
297                                                    budget,
298                                                    offset + almost_total);
299
300         if let Some(ref mut s) = last_rewrite {
301             ::std::mem::swap(s, last);
302             true
303         } else {
304             false
305         }
306     } else {
307         unreachable!();
308     }
309 }
310
311 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
312 // `.c`.
313 fn rewrite_chain_subexpr(expr: &ast::Expr,
314                          span: Span,
315                          context: &RewriteContext,
316                          width: usize,
317                          offset: Indent)
318                          -> Option<String> {
319     match expr.node {
320         ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) => {
321             let inner = &RewriteContext { block_indent: offset, ..*context };
322             rewrite_method_call(method_name.node,
323                                 types,
324                                 expressions,
325                                 span,
326                                 inner,
327                                 width,
328                                 offset)
329         }
330         ast::ExprKind::Field(_, ref field) => {
331             let s = format!(".{}", field.node);
332             if s.len() <= width {
333                 Some(s)
334             } else {
335                 None
336             }
337         }
338         ast::ExprKind::TupField(_, ref field) => {
339             let s = format!(".{}", field.node);
340             if s.len() <= width {
341                 Some(s)
342             } else {
343                 None
344             }
345         }
346         _ => unreachable!(),
347     }
348 }
349
350 // Determines if we can continue formatting a given expression on the same line.
351 fn is_continuable(expr: &ast::Expr) -> bool {
352     match expr.node {
353         ast::ExprKind::Path(..) => true,
354         _ => false,
355     }
356 }
357
358 fn rewrite_method_call(method_name: ast::Ident,
359                        types: &[ptr::P<ast::Ty>],
360                        args: &[ptr::P<ast::Expr>],
361                        span: Span,
362                        context: &RewriteContext,
363                        width: usize,
364                        offset: Indent)
365                        -> Option<String> {
366     let (lo, type_str) = if types.is_empty() {
367         (args[0].span.hi, String::new())
368     } else {
369         let type_list: Vec<_> = try_opt!(types.iter()
370                                               .map(|ty| ty.rewrite(context, width, offset))
371                                               .collect());
372
373         (types.last().unwrap().span.hi, format!("::<{}>", type_list.join(", ")))
374     };
375
376     let callee_str = format!(".{}{}", method_name, type_str);
377     let span = mk_sp(lo, span.hi);
378
379     rewrite_call(context, &callee_str, &args[1..], span, width, offset)
380 }