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