]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
Run clippy
[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, method calls, and try shorthand (?).
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 use Indent;
85 use rewrite::{Rewrite, RewriteContext};
86 use utils::{wrap_str, first_line_width};
87 use expr::rewrite_call;
88 use config::BlockIndentStyle;
89 use macros::convert_try_mac;
90
91 use std::iter;
92 use syntax::{ast, ptr};
93 use syntax::codemap::{mk_sp, Span};
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, context);
102
103     // Bail out if the chain is just try sugar, i.e., an expression followed by
104     // any number of `?`s.
105     if chain_only_try(&subexpr_list) {
106         return rewrite_try(&parent, subexpr_list.len(), context, width, offset);
107     }
108
109     // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
110     let parent_block_indent = chain_base_indent(context, offset);
111     let parent_context = &RewriteContext { block_indent: parent_block_indent, ..*context };
112     let parent_rewrite = try_opt!(parent.rewrite(parent_context, width, offset));
113
114     // Decide how to layout the rest of the chain. `extend` is true if we can
115     // put the first non-parent item on the same line as the parent.
116     let (indent, extend) = if !parent_rewrite.contains('\n') && is_continuable(&parent) ||
117                               parent_rewrite.len() <= context.config.tab_spaces {
118
119         let indent = if let ast::ExprKind::Try(..) = subexpr_list.last().unwrap().node {
120             parent_block_indent.block_indent(context.config)
121         } else {
122             chain_indent(context, offset + Indent::new(0, parent_rewrite.len()))
123         };
124         (indent, true)
125     } else if is_block_expr(&parent, &parent_rewrite) {
126         // The parent is a block, so align the rest of the chain with the closing
127         // brace.
128         (parent_block_indent, false)
129     } else if parent_rewrite.contains('\n') {
130         (chain_indent(context, parent_block_indent.block_indent(context.config)), false)
131     } else {
132         (chain_indent_newline(context, offset + Indent::new(0, parent_rewrite.len())), false)
133     };
134
135     let max_width = try_opt!((width + offset.width()).checked_sub(indent.width()));
136     let mut rewrites = try_opt!(subexpr_list.iter()
137         .rev()
138         .map(|e| rewrite_chain_subexpr(e, total_span, context, max_width, indent))
139         .collect::<Option<Vec<_>>>());
140
141     // Total of all items excluding the last.
142     let almost_total = rewrites[..rewrites.len() - 1]
143         .iter()
144         .fold(0, |a, b| a + first_line_width(b)) + parent_rewrite.len();
145     let total_width = almost_total + first_line_width(rewrites.last().unwrap());
146
147     let veto_single_line = if context.config.take_source_hints && subexpr_list.len() > 1 {
148         // Look at the source code. Unless all chain elements start on the same
149         // line, we won't consider putting them on a single line either.
150         let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
151         let first_span = context.snippet(subexpr_list[1].span);
152         let last_iter = last_span.chars().take_while(|c| c.is_whitespace());
153
154         first_span.chars().chain(last_iter).any(|c| c == '\n')
155     } else {
156         false
157     };
158
159     let mut fits_single_line = !veto_single_line && total_width <= width;
160     if fits_single_line {
161         let len = rewrites.len();
162         let (init, last) = rewrites.split_at_mut(len - 1);
163         fits_single_line = init.iter().all(|s| !s.contains('\n'));
164
165         if fits_single_line {
166             fits_single_line = match expr.node {
167                 ref e @ ast::ExprKind::MethodCall(..) if context.config.chains_overflow_last => {
168                     rewrite_method_call_with_overflow(e,
169                                                       &mut last[0],
170                                                       almost_total,
171                                                       width,
172                                                       total_span,
173                                                       context,
174                                                       offset)
175                 }
176                 _ => !last[0].contains('\n'),
177             }
178         }
179     }
180
181     let connector = if fits_single_line && !parent_rewrite.contains('\n') {
182         // Yay, we can put everything on one line.
183         String::new()
184     } else {
185         // Use new lines.
186         format!("\n{}", indent.to_string(context.config))
187     };
188
189     let first_connector = if extend || subexpr_list.is_empty() {
190         ""
191     } else if let ast::ExprKind::Try(_) = subexpr_list[0].node {
192         ""
193     } else {
194         &*connector
195     };
196
197     wrap_str(format!("{}{}{}",
198                      parent_rewrite,
199                      first_connector,
200                      join_rewrites(&rewrites, &subexpr_list, &connector)),
201              context.config.max_width,
202              width,
203              offset)
204 }
205
206 // True if the chain is only `?`s.
207 fn chain_only_try(exprs: &[ast::Expr]) -> bool {
208     exprs.iter().all(|e| if let ast::ExprKind::Try(_) = e.node {
209         true
210     } else {
211         false
212     })
213 }
214
215 pub fn rewrite_try(expr: &ast::Expr,
216                    try_count: usize,
217                    context: &RewriteContext,
218                    width: usize,
219                    offset: Indent)
220                    -> Option<String> {
221     let sub_expr = try_opt!(expr.rewrite(context, width - try_count, offset));
222     Some(format!("{}{}",
223                  sub_expr,
224                  iter::repeat("?").take(try_count).collect::<String>()))
225 }
226
227 fn join_rewrites(rewrites: &[String], subexps: &[ast::Expr], connector: &str) -> String {
228     let mut rewrite_iter = rewrites.iter();
229     let mut result = rewrite_iter.next().unwrap().clone();
230     let mut subexpr_iter = subexps.iter().rev();
231     subexpr_iter.next();
232
233     for (rewrite, expr) in rewrite_iter.zip(subexpr_iter) {
234         match expr.node {
235             ast::ExprKind::Try(_) => (),
236             _ => result.push_str(connector),
237         };
238         result.push_str(&rewrite[..]);
239     }
240
241     result
242 }
243
244 // States whether an expression's last line exclusively consists of closing
245 // parens, braces, and brackets in its idiomatic formatting.
246 fn is_block_expr(expr: &ast::Expr, repr: &str) -> bool {
247     match expr.node {
248         ast::ExprKind::Struct(..) |
249         ast::ExprKind::While(..) |
250         ast::ExprKind::WhileLet(..) |
251         ast::ExprKind::If(..) |
252         ast::ExprKind::IfLet(..) |
253         ast::ExprKind::Block(..) |
254         ast::ExprKind::Loop(..) |
255         ast::ExprKind::ForLoop(..) |
256         ast::ExprKind::Match(..) => repr.contains('\n'),
257         ast::ExprKind::Paren(ref expr) |
258         ast::ExprKind::Binary(_, _, ref expr) |
259         ast::ExprKind::Index(_, ref expr) |
260         ast::ExprKind::Unary(_, ref expr) => is_block_expr(expr, repr),
261         _ => false,
262     }
263 }
264
265 // Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
266 // E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
267 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> (ast::Expr, Vec<ast::Expr>) {
268     let mut subexpr_list = vec![expr.clone()];
269
270     while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
271         subexpr_list.push(subexpr.clone());
272     }
273
274     let parent = subexpr_list.pop().unwrap();
275     (parent, subexpr_list)
276 }
277
278 fn chain_base_indent(context: &RewriteContext, offset: Indent) -> Indent {
279     match context.config.chain_base_indent {
280         BlockIndentStyle::Visual => offset,
281         BlockIndentStyle::Inherit => context.block_indent,
282         BlockIndentStyle::Tabbed => context.block_indent.block_indent(context.config),
283     }
284 }
285
286 fn chain_indent(context: &RewriteContext, offset: Indent) -> Indent {
287     match context.config.chain_indent {
288         BlockIndentStyle::Visual => offset,
289         BlockIndentStyle::Inherit => context.block_indent,
290         BlockIndentStyle::Tabbed => context.block_indent.block_indent(context.config),
291     }
292 }
293
294 // Ignores visual indenting because this function should be called where it is
295 // not possible to use visual indentation because we are starting on a newline.
296 fn chain_indent_newline(context: &RewriteContext, _offset: Indent) -> Indent {
297     match context.config.chain_indent {
298         BlockIndentStyle::Inherit => context.block_indent,
299         BlockIndentStyle::Visual | BlockIndentStyle::Tabbed => {
300             context.block_indent.block_indent(context.config)
301         }
302     }
303 }
304
305 fn rewrite_method_call_with_overflow(expr_kind: &ast::ExprKind,
306                                      last: &mut String,
307                                      almost_total: usize,
308                                      width: usize,
309                                      total_span: Span,
310                                      context: &RewriteContext,
311                                      offset: Indent)
312                                      -> bool {
313     if let &ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) = expr_kind {
314         let budget = match width.checked_sub(almost_total) {
315             Some(b) => b,
316             None => return false,
317         };
318         let mut last_rewrite = rewrite_method_call(method_name.node,
319                                                    types,
320                                                    expressions,
321                                                    total_span,
322                                                    context,
323                                                    budget,
324                                                    offset + almost_total);
325
326         if let Some(ref mut s) = last_rewrite {
327             ::std::mem::swap(s, last);
328             true
329         } else {
330             false
331         }
332     } else {
333         unreachable!();
334     }
335 }
336
337 // Returns the expression's subexpression, if it exists. When the subexpr
338 // is a try! macro, we'll convert it to shorthand when the option is set.
339 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
340     match expr.node {
341         ast::ExprKind::MethodCall(_, _, ref expressions) => {
342             Some(convert_try(&expressions[0], context))
343         }
344         ast::ExprKind::TupField(ref subexpr, _) |
345         ast::ExprKind::Field(ref subexpr, _) |
346         ast::ExprKind::Try(ref subexpr) => Some(convert_try(subexpr, context)),
347         _ => None,
348     }
349 }
350
351 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
352     match expr.node {
353         ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand => {
354             if let Some(subexpr) = convert_try_mac(mac, context) {
355                 subexpr
356             } else {
357                 expr.clone()
358             }
359         }
360         _ => expr.clone(),
361     }
362 }
363
364 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
365 // `.c`.
366 fn rewrite_chain_subexpr(expr: &ast::Expr,
367                          span: Span,
368                          context: &RewriteContext,
369                          width: usize,
370                          offset: Indent)
371                          -> Option<String> {
372     match expr.node {
373         ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) => {
374             let inner = &RewriteContext { block_indent: offset, ..*context };
375             rewrite_method_call(method_name.node,
376                                 types,
377                                 expressions,
378                                 span,
379                                 inner,
380                                 width,
381                                 offset)
382         }
383         ast::ExprKind::Field(_, ref field) => {
384             let s = format!(".{}", field.node);
385             if s.len() <= width { Some(s) } else { None }
386         }
387         ast::ExprKind::TupField(_, ref field) => {
388             let s = format!(".{}", field.node);
389             if s.len() <= width { Some(s) } else { None }
390         }
391         ast::ExprKind::Try(_) => if width >= 1 { Some("?".into()) } else { None },
392         _ => unreachable!(),
393     }
394 }
395
396 // Determines if we can continue formatting a given expression on the same line.
397 fn is_continuable(expr: &ast::Expr) -> bool {
398     match expr.node {
399         ast::ExprKind::Path(..) => true,
400         _ => false,
401     }
402 }
403
404 fn rewrite_method_call(method_name: ast::Ident,
405                        types: &[ptr::P<ast::Ty>],
406                        args: &[ptr::P<ast::Expr>],
407                        span: Span,
408                        context: &RewriteContext,
409                        width: usize,
410                        offset: Indent)
411                        -> Option<String> {
412     let (lo, type_str) = if types.is_empty() {
413         (args[0].span.hi, String::new())
414     } else {
415         let type_list: Vec<_> = try_opt!(types.iter()
416             .map(|ty| ty.rewrite(context, width, offset))
417             .collect());
418
419         (types.last().unwrap().span.hi, format!("::<{}>", type_list.join(", ")))
420     };
421
422     let callee_str = format!(".{}{}", method_name, type_str);
423     let span = mk_sp(lo, span.hi);
424
425     rewrite_call(context, &callee_str, &args[1..], span, width, offset)
426 }