]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
WIP
[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, Shape};
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, context: &RewriteContext, shape: Shape) -> Option<String> {
96     debug!("rewrite_chain {:?}", shape);
97     let total_span = expr.span;
98     let (parent, subexpr_list) = make_subexpr_list(expr, context);
99
100     // Bail out if the chain is just try sugar, i.e., an expression followed by
101     // any number of `?`s.
102     if chain_only_try(&subexpr_list) {
103         return rewrite_try(&parent, subexpr_list.len(), context, shape);
104     }
105
106     // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
107     let mut parent_shape = shape;
108     if is_block_expr(&parent, "\n") {
109         parent_shape = chain_base_indent(context, shape);
110     }
111     let parent_rewrite = try_opt!(parent.rewrite(context, parent_shape));
112
113     // Decide how to layout the rest of the chain. `extend` is true if we can
114     // put the first non-parent item on the same line as the parent.
115     let (nested_shape, extend) = if !parent_rewrite.contains('\n') && is_continuable(&parent) {
116         let nested_shape = if let ast::ExprKind::Try(..) = subexpr_list.last().unwrap().node {
117             parent_shape.block_indent(context.config.tab_spaces)
118         } else {
119             chain_indent(context, shape.add_offset(parent_rewrite.len()))
120         };
121         (nested_shape, true)
122     } else if is_block_expr(&parent, &parent_rewrite) {
123         // The parent is a block, so align the rest of the chain with the closing
124         // brace.
125         (parent_shape, false)
126     } else if parent_rewrite.contains('\n') {
127         (chain_indent(context, parent_shape.block_indent(context.config.tab_spaces)), false)
128     } else {
129         (chain_indent_newline(context, shape.add_offset(parent_rewrite.len())), false)
130     };
131
132     let max_width = try_opt!((shape.width + shape.indent.width() + shape.offset).checked_sub(nested_shape.indent.width() + nested_shape.offset));
133     // The alignement in the shape is only used if we start the item on a new
134     // line, so we don't need to preserve the offset.
135     let child_shape = Shape { width: max_width, ..nested_shape };
136     debug!("child_shape {:?}", child_shape);
137     let mut rewrites = try_opt!(subexpr_list.iter()
138         .rev()
139         .map(|e| rewrite_chain_subexpr(e, total_span, context, child_shape))
140         .collect::<Option<Vec<_>>>());
141
142     // Total of all items excluding the last.
143     let almost_total = rewrites[..rewrites.len() - 1]
144         .iter()
145         .fold(0, |a, b| a + first_line_width(b)) + parent_rewrite.len();
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 && almost_total <= shape.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                                                       total_span,
172                                                       context,
173                                                       shape)
174                 }
175                 _ => !last[0].contains('\n'),
176             }
177         }
178     }
179
180     let connector = if fits_single_line && !parent_rewrite.contains('\n') {
181         // Yay, we can put everything on one line.
182         String::new()
183     } else {
184         // Use new lines.
185         format!("\n{}", nested_shape.indent.to_string(context.config))
186     };
187
188     let first_connector = if extend || subexpr_list.is_empty() {
189         ""
190     } else if let ast::ExprKind::Try(_) = subexpr_list[0].node {
191         ""
192     } else {
193         &*connector
194     };
195
196     wrap_str(format!("{}{}{}",
197                      parent_rewrite,
198                      first_connector,
199                      join_rewrites(&rewrites, &subexpr_list, &connector)),
200              context.config.max_width,
201              shape)
202 }
203
204 // True if the chain is only `?`s.
205 fn chain_only_try(exprs: &[ast::Expr]) -> bool {
206     exprs.iter().all(|e| if let ast::ExprKind::Try(_) = e.node {
207         true
208     } else {
209         false
210     })
211 }
212
213 pub fn rewrite_try(expr: &ast::Expr,
214                    try_count: usize,
215                    context: &RewriteContext,
216                    shape: Shape)
217                    -> Option<String> {
218     let sub_expr = try_opt!(expr.rewrite(context, try_opt!(shape.sub_width(try_count))));
219     Some(format!("{}{}",
220                  sub_expr,
221                  iter::repeat("?").take(try_count).collect::<String>()))
222 }
223
224 fn join_rewrites(rewrites: &[String], subexps: &[ast::Expr], connector: &str) -> String {
225     let mut rewrite_iter = rewrites.iter();
226     let mut result = rewrite_iter.next().unwrap().clone();
227     let mut subexpr_iter = subexps.iter().rev();
228     subexpr_iter.next();
229
230     for (rewrite, expr) in rewrite_iter.zip(subexpr_iter) {
231         match expr.node {
232             ast::ExprKind::Try(_) => (),
233             _ => result.push_str(connector),
234         };
235         result.push_str(&rewrite[..]);
236     }
237
238     result
239 }
240
241 // States whether an expression's last line exclusively consists of closing
242 // parens, braces, and brackets in its idiomatic formatting.
243 fn is_block_expr(expr: &ast::Expr, repr: &str) -> bool {
244     match expr.node {
245         ast::ExprKind::Struct(..) |
246         ast::ExprKind::While(..) |
247         ast::ExprKind::WhileLet(..) |
248         ast::ExprKind::If(..) |
249         ast::ExprKind::IfLet(..) |
250         ast::ExprKind::Block(..) |
251         ast::ExprKind::Loop(..) |
252         ast::ExprKind::ForLoop(..) |
253         ast::ExprKind::Match(..) => repr.contains('\n'),
254         ast::ExprKind::Paren(ref expr) |
255         ast::ExprKind::Binary(_, _, ref expr) |
256         ast::ExprKind::Index(_, ref expr) |
257         ast::ExprKind::Unary(_, ref expr) => is_block_expr(expr, repr),
258         _ => false,
259     }
260 }
261
262 // Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
263 // E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
264 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> (ast::Expr, Vec<ast::Expr>) {
265     let mut subexpr_list = vec![expr.clone()];
266
267     while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
268         subexpr_list.push(subexpr.clone());
269     }
270
271     let parent = subexpr_list.pop().unwrap();
272     (parent, subexpr_list)
273 }
274
275 fn chain_base_indent(context: &RewriteContext, shape: Shape) -> Shape {
276     match context.config.chain_base_indent {
277         BlockIndentStyle::Visual => shape,
278         BlockIndentStyle::Inherit => shape.block_indent(0),
279         BlockIndentStyle::Tabbed => shape.block_indent(context.config.tab_spaces),
280     }
281 }
282
283 fn chain_indent(context: &RewriteContext, shape: Shape) -> Shape {
284     match context.config.chain_indent {
285         BlockIndentStyle::Visual => shape,
286         BlockIndentStyle::Inherit => shape.block_indent(0),
287         BlockIndentStyle::Tabbed => shape.block_indent(context.config.tab_spaces),
288     }
289 }
290
291 // Ignores visual indenting because this function should be called where it is
292 // not possible to use visual indentation because we are starting on a newline.
293 fn chain_indent_newline(context: &RewriteContext, shape: Shape) -> Shape {
294     match context.config.chain_indent {
295         BlockIndentStyle::Inherit => shape.block_indent(0),
296         BlockIndentStyle::Visual | BlockIndentStyle::Tabbed => {
297             shape.block_indent(context.config.tab_spaces)
298         }
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<_> = try_opt!(types.iter()
416             .map(|ty| ty.rewrite(context, shape))
417             .collect());
418
419         let type_str = if context.config.spaces_within_angle_brackets && type_list.len() > 0 {
420             format!("::< {} >", type_list.join(", "))
421         } else {
422             format!("::<{}>", type_list.join(", "))
423         };
424
425         (types.last().unwrap().span.hi, type_str)
426     };
427
428     let callee_str = format!(".{}{}", method_name, type_str);
429     let span = mk_sp(lo, span.hi);
430
431     rewrite_call(context, &callee_str, &args[1..], span, shape)
432 }