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