]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
Merge pull request #1588 from topecongiro/nesting-macro
[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::IndentStyle;
84 use macros::convert_try_mac;
85
86 use std::cmp::min;
87 use std::iter;
88 use syntax::{ast, ptr};
89 use syntax::codemap::{mk_sp, Span};
90
91 pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -> Option<String> {
92     debug!("rewrite_chain {:?}", shape);
93     let total_span = expr.span;
94     let (parent, subexpr_list) = make_subexpr_list(expr, context);
95
96     // Bail out if the chain is just try sugar, i.e., an expression followed by
97     // any number of `?`s.
98     if chain_only_try(&subexpr_list) {
99         return rewrite_try(&parent, subexpr_list.len(), context, shape);
100     }
101     let trailing_try_num = subexpr_list
102         .iter()
103         .take_while(|e| match e.node {
104                         ast::ExprKind::Try(..) => true,
105                         _ => false,
106                     })
107         .count();
108
109     // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
110     let parent_shape = if is_block_expr(context, &parent, "\n") {
111         match context.config.chain_indent() {
112             IndentStyle::Visual => shape.visual_indent(0),
113             IndentStyle::Block => shape.block(),
114         }
115     } else {
116         shape
117     };
118     let parent_rewrite = try_opt!(parent.rewrite(context, parent_shape));
119     let parent_rewrite_contains_newline = parent_rewrite.contains('\n');
120
121     // Decide how to layout the rest of the chain. `extend` is true if we can
122     // put the first non-parent item on the same line as the parent.
123     let first_subexpr_is_try = match subexpr_list.last().unwrap().node {
124         ast::ExprKind::Try(..) => true,
125         _ => false,
126     };
127     let (nested_shape, extend) = if !parent_rewrite_contains_newline && is_continuable(&parent) {
128         let nested_shape = if first_subexpr_is_try {
129             parent_shape.block_indent(context.config.tab_spaces())
130         } else {
131             chain_indent(context, shape.add_offset(parent_rewrite.len()))
132         };
133         (nested_shape,
134          context.config.chain_indent() == IndentStyle::Visual ||
135          parent_rewrite.len() <= context.config.tab_spaces())
136     } else if is_block_expr(context, &parent, &parent_rewrite) {
137         match context.config.chain_indent() {
138             // Try to put the first child on the same line with parent's last line
139             IndentStyle::Block => (parent_shape.block_indent(context.config.tab_spaces()), true),
140             // The parent is a block, so align the rest of the chain with the closing
141             // brace.
142             IndentStyle::Visual => (parent_shape, false),
143         }
144     } else if parent_rewrite_contains_newline {
145         (chain_indent(context, parent_shape), false)
146     } else {
147         (shape.block_indent(context.config.tab_spaces()), false)
148     };
149
150     let other_child_shape = nested_shape.with_max_width(context.config);
151
152     let first_child_shape = if extend {
153         let overhead = last_line_width(&parent_rewrite);
154         let offset = parent_rewrite.lines().rev().next().unwrap().trim().len();
155         match context.config.chain_indent() {
156             IndentStyle::Visual => try_opt!(parent_shape.offset_left(overhead)),
157             IndentStyle::Block => try_opt!(parent_shape.block().offset_left(offset)),
158         }
159     } else {
160         other_child_shape
161     };
162     debug!("child_shapes {:?} {:?}",
163            first_child_shape,
164            other_child_shape);
165
166     let child_shape_iter =
167         Some(first_child_shape)
168             .into_iter()
169             .chain(::std::iter::repeat(other_child_shape).take(subexpr_list.len() - 1));
170     let iter = subexpr_list.iter().rev().zip(child_shape_iter);
171     let mut rewrites =
172         try_opt!(iter.map(|(e, shape)| rewrite_chain_subexpr(e, total_span, context, shape))
173                      .collect::<Option<Vec<_>>>());
174
175     // Total of all items excluding the last.
176     let last_non_try_index = rewrites.len() - (1 + trailing_try_num);
177     let almost_total = rewrites[..last_non_try_index]
178         .iter()
179         .fold(0, |a, b| a + first_line_width(b)) + parent_rewrite.len();
180     let one_line_len = rewrites.iter().fold(0, |a, r| a + first_line_width(r)) +
181                        parent_rewrite.len();
182
183     let one_line_budget = min(shape.width, context.config.chain_one_line_max());
184     let veto_single_line = if one_line_len > one_line_budget {
185         if rewrites.len() > 1 {
186             true
187         } else if rewrites.len() == 1 {
188             context.config.chain_split_single_child() || one_line_len > shape.width
189         } else {
190             false
191         }
192     } else if context.config.take_source_hints() && subexpr_list.len() > 1 {
193         // Look at the source code. Unless all chain elements start on the same
194         // line, we won't consider putting them on a single line either.
195         let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
196         let first_span = context.snippet(subexpr_list[1].span);
197         let last_iter = last_span.chars().take_while(|c| c.is_whitespace());
198
199         first_span.chars().chain(last_iter).any(|c| c == '\n')
200     } else {
201         false
202     };
203
204     let mut fits_single_line = !veto_single_line && almost_total <= shape.width;
205     if fits_single_line {
206         let len = rewrites.len();
207         let (init, last) = rewrites.split_at_mut(len - (1 + trailing_try_num));
208         fits_single_line = init.iter().all(|s| !s.contains('\n'));
209
210         if fits_single_line {
211             fits_single_line = match expr.node {
212                 ref e @ ast::ExprKind::MethodCall(..) => {
213                     if rewrite_method_call_with_overflow(e,
214                                                          &mut last[0],
215                                                          almost_total,
216                                                          total_span,
217                                                          context,
218                                                          shape) {
219                         // If the first line of the last method does not fit into a single line
220                         // after the others, allow new lines.
221                         almost_total + first_line_width(&last[0]) < context.config.max_width()
222                     } else {
223                         false
224                     }
225                 }
226                 _ => !last[0].contains('\n'),
227             }
228         }
229     }
230
231     // Try overflowing the last element if we are using block indent.
232     if !fits_single_line && context.config.fn_call_style() == IndentStyle::Block {
233         let (init, last) = rewrites.split_at_mut(last_non_try_index);
234         let almost_single_line = init.iter().all(|s| !s.contains('\n'));
235         if almost_single_line {
236             let overflow_shape = Shape {
237                 width: one_line_budget,
238                 ..parent_shape
239             };
240             fits_single_line = rewrite_last_child_with_overflow(context,
241                                                                 &subexpr_list[trailing_try_num],
242                                                                 overflow_shape,
243                                                                 total_span,
244                                                                 almost_total,
245                                                                 one_line_budget,
246                                                                 &mut last[0]);
247         }
248     }
249
250     let connector = if fits_single_line && !parent_rewrite_contains_newline {
251         // Yay, we can put everything on one line.
252         String::new()
253     } else {
254         // Use new lines.
255         format!("\n{}", nested_shape.indent.to_string(context.config))
256     };
257
258     let first_connector = if subexpr_list.is_empty() {
259         ""
260     } else if extend || first_subexpr_is_try {
261         // 1 = ";", being conservative here.
262         if last_line_width(&parent_rewrite) + first_line_width(&rewrites[0]) + 1 <=
263            context.config.max_width() {
264             ""
265         } else {
266             &*connector
267         }
268     } else {
269         &*connector
270     };
271
272     wrap_str(format!("{}{}{}",
273                      parent_rewrite,
274                      first_connector,
275                      join_rewrites(&rewrites, &subexpr_list, &connector)),
276              context.config.max_width(),
277              shape)
278 }
279
280 // True if the chain is only `?`s.
281 fn chain_only_try(exprs: &[ast::Expr]) -> bool {
282     exprs.iter().all(|e| if let ast::ExprKind::Try(_) = e.node {
283                          true
284                      } else {
285                          false
286                      })
287 }
288
289 // Try to rewrite and replace the last non-try child. Return `true` if
290 // replacing succeeds.
291 fn rewrite_last_child_with_overflow(context: &RewriteContext,
292                                     expr: &ast::Expr,
293                                     shape: Shape,
294                                     span: Span,
295                                     almost_total: usize,
296                                     one_line_budget: usize,
297                                     last_child: &mut String)
298                                     -> bool {
299     if let Some(shape) = shape.shrink_left(almost_total) {
300         if let Some(ref mut rw) = rewrite_chain_subexpr(expr, span, context, shape) {
301             if almost_total + first_line_width(rw) <= one_line_budget {
302                 ::std::mem::swap(last_child, rw);
303                 return true;
304             }
305         }
306     }
307     false
308 }
309
310 pub fn rewrite_try(expr: &ast::Expr,
311                    try_count: usize,
312                    context: &RewriteContext,
313                    shape: Shape)
314                    -> Option<String> {
315     let sub_expr = try_opt!(expr.rewrite(context, try_opt!(shape.sub_width(try_count))));
316     Some(format!("{}{}",
317                  sub_expr,
318                  iter::repeat("?").take(try_count).collect::<String>()))
319 }
320
321 fn join_rewrites(rewrites: &[String], subexps: &[ast::Expr], connector: &str) -> String {
322     let mut rewrite_iter = rewrites.iter();
323     let mut result = rewrite_iter.next().unwrap().clone();
324     let mut subexpr_iter = subexps.iter().rev();
325     subexpr_iter.next();
326
327     for (rewrite, expr) in rewrite_iter.zip(subexpr_iter) {
328         match expr.node {
329             ast::ExprKind::Try(_) => (),
330             _ => result.push_str(connector),
331         };
332         result.push_str(&rewrite[..]);
333     }
334
335     result
336 }
337
338 // States whether an expression's last line exclusively consists of closing
339 // parens, braces, and brackets in its idiomatic formatting.
340 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
341     match expr.node {
342         ast::ExprKind::Call(..) => {
343             context.config.fn_call_style() == IndentStyle::Block && repr.contains('\n')
344         }
345         ast::ExprKind::Struct(..) |
346         ast::ExprKind::While(..) |
347         ast::ExprKind::WhileLet(..) |
348         ast::ExprKind::If(..) |
349         ast::ExprKind::IfLet(..) |
350         ast::ExprKind::Block(..) |
351         ast::ExprKind::Loop(..) |
352         ast::ExprKind::ForLoop(..) |
353         ast::ExprKind::Match(..) => repr.contains('\n'),
354         ast::ExprKind::Paren(ref expr) |
355         ast::ExprKind::Binary(_, _, ref expr) |
356         ast::ExprKind::Index(_, ref expr) |
357         ast::ExprKind::Unary(_, ref expr) => is_block_expr(context, expr, repr),
358         _ => false,
359     }
360 }
361
362 // Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
363 // E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
364 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> (ast::Expr, Vec<ast::Expr>) {
365     let mut subexpr_list = vec![expr.clone()];
366
367     while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
368         subexpr_list.push(subexpr.clone());
369     }
370
371     let parent = subexpr_list.pop().unwrap();
372     (parent, subexpr_list)
373 }
374
375 fn chain_indent(context: &RewriteContext, shape: Shape) -> Shape {
376     match context.config.chain_indent() {
377         IndentStyle::Visual => shape.visual_indent(0),
378         IndentStyle::Block => shape.block_indent(context.config.tab_spaces()),
379     }
380 }
381
382 fn rewrite_method_call_with_overflow(expr_kind: &ast::ExprKind,
383                                      last: &mut String,
384                                      almost_total: usize,
385                                      total_span: Span,
386                                      context: &RewriteContext,
387                                      shape: Shape)
388                                      -> bool {
389     if let &ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) = expr_kind {
390         let shape = match shape.shrink_left(almost_total) {
391             Some(b) => b,
392             None => return false,
393         };
394         let mut last_rewrite = rewrite_method_call(method_name.node,
395                                                    types,
396                                                    expressions,
397                                                    total_span,
398                                                    context,
399                                                    shape);
400
401         if let Some(ref mut s) = last_rewrite {
402             ::std::mem::swap(s, last);
403             true
404         } else {
405             false
406         }
407     } else {
408         unreachable!();
409     }
410 }
411
412 // Returns the expression's subexpression, if it exists. When the subexpr
413 // is a try! macro, we'll convert it to shorthand when the option is set.
414 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
415     match expr.node {
416         ast::ExprKind::MethodCall(_, _, ref expressions) => {
417             Some(convert_try(&expressions[0], context))
418         }
419         ast::ExprKind::TupField(ref subexpr, _) |
420         ast::ExprKind::Field(ref subexpr, _) |
421         ast::ExprKind::Try(ref subexpr) => Some(convert_try(subexpr, context)),
422         _ => None,
423     }
424 }
425
426 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
427     match expr.node {
428         ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
429             if let Some(subexpr) = convert_try_mac(mac, context) {
430                 subexpr
431             } else {
432                 expr.clone()
433             }
434         }
435         _ => expr.clone(),
436     }
437 }
438
439 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
440 // `.c`.
441 fn rewrite_chain_subexpr(expr: &ast::Expr,
442                          span: Span,
443                          context: &RewriteContext,
444                          shape: Shape)
445                          -> Option<String> {
446     let rewrite_element = |expr_str: String| if expr_str.len() <= shape.width {
447         Some(expr_str)
448     } else {
449         None
450     };
451
452     match expr.node {
453         ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) => {
454             rewrite_method_call(method_name.node, types, expressions, span, context, shape)
455         }
456         ast::ExprKind::Field(_, ref field) => rewrite_element(format!(".{}", field.node)),
457         ast::ExprKind::TupField(_, ref field) => rewrite_element(format!(".{}", field.node)),
458         ast::ExprKind::Try(_) => rewrite_element(String::from("?")),
459         _ => unreachable!(),
460     }
461 }
462
463 // Determines if we can continue formatting a given expression on the same line.
464 fn is_continuable(expr: &ast::Expr) -> bool {
465     match expr.node {
466         ast::ExprKind::Path(..) => true,
467         _ => false,
468     }
469 }
470
471 fn rewrite_method_call(method_name: ast::Ident,
472                        types: &[ptr::P<ast::Ty>],
473                        args: &[ptr::P<ast::Expr>],
474                        span: Span,
475                        context: &RewriteContext,
476                        shape: Shape)
477                        -> Option<String> {
478     let (lo, type_str) = if types.is_empty() {
479         (args[0].span.hi, String::new())
480     } else {
481         let type_list: Vec<_> =
482             try_opt!(types.iter().map(|ty| ty.rewrite(context, shape)).collect());
483
484         let type_str = if context.config.spaces_within_angle_brackets() && type_list.len() > 0 {
485             format!("::< {} >", type_list.join(", "))
486         } else {
487             format!("::<{}>", type_list.join(", "))
488         };
489
490         (types.last().unwrap().span.hi, type_str)
491     };
492
493     let callee_str = format!(".{}{}", method_name, type_str);
494     let span = mk_sp(lo, span.hi);
495
496     rewrite_call(context, &callee_str, &args[1..], span, shape)
497 }