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