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