]> git.lizzy.rs Git - rust.git/blob - src/chains.rs
a407fdda112d1bef34982d67b47ddd034ff72225
[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 //! Block:
28 //!
29 //! ```ignore
30 //! let foo = {
31 //!     aaaa;
32 //!     bbb;
33 //!     ccc
34 //! }.bar
35 //!     .baz();
36 //! ```
37 //!
38 //! Visual:
39 //!
40 //! ```ignore
41 //! let foo = {
42 //!               aaaa;
43 //!               bbb;
44 //!               ccc
45 //!           }
46 //!           .bar
47 //!           .baz();
48 //! ```
49 //!
50 //! If the first item in the chain is a block expression, we align the dots with
51 //! the braces.
52 //! Block:
53 //!
54 //! ```ignore
55 //! let a = foo.bar
56 //!     .baz()
57 //!     .qux
58 //! ```
59 //!
60 //! Visual:
61 //!
62 //! ```ignore
63 //! let a = foo.bar
64 //!            .baz()
65 //!            .qux
66 //! ```
67
68 use config::IndentStyle;
69 use expr::rewrite_call;
70 use macros::convert_try_mac;
71 use rewrite::{Rewrite, RewriteContext};
72 use shape::Shape;
73 use spanned::Spanned;
74 use utils::{
75     first_line_width, last_line_extendable, last_line_width, mk_sp, trimmed_last_line_width,
76     wrap_str,
77 };
78
79 use std::borrow::Cow;
80 use std::cmp::min;
81
82 use syntax::codemap::Span;
83 use syntax::{ast, ptr};
84
85 pub fn rewrite_chain(expr: &ast::Expr, context: &RewriteContext, shape: Shape) -> Option<String> {
86     debug!("rewrite_chain {:?}", shape);
87     let chain = Chain::from_ast(expr, context);
88     // If this is just an expression with some `?`s, then format it trivially and
89     // return early.
90     if chain.children.is_empty() {
91         let rewrite = chain.parent.expr.rewrite(context, shape.sub_width(chain.parent.tries)?)?;
92         return Some(format!("{}{}", rewrite, "?".repeat(chain.parent.tries)));
93     }
94
95     match context.config.indent_style() {
96         IndentStyle::Block => rewrite_chain_block(chain, context, shape),
97         IndentStyle::Visual => rewrite_chain_visual(chain, context, shape),
98     }
99 }
100
101 // An expression plus trailing `?`s to be formatted together.
102 struct ChainItem {
103     expr: ast::Expr,
104     tries: usize,
105 }
106
107 struct Chain {
108     parent: ChainItem,
109     // TODO do we need to clone the exprs?
110     children: Vec<ChainItem>,
111 }
112
113 impl Chain {
114     fn from_ast(expr: &ast::Expr, context: &RewriteContext) -> Chain {
115         let mut subexpr_list = make_subexpr_list(expr, context);
116
117         // Un-parse the expression tree into ChainItems
118         let mut children = vec![];
119         let mut sub_tries = 0;
120         loop {
121             if subexpr_list.is_empty() {
122                 break;
123             }
124
125             let subexpr = subexpr_list.pop().unwrap();
126             match subexpr.node {
127                 ast::ExprKind::Try(_) => sub_tries += 1,
128                 _ => {
129                     children.push(ChainItem {
130                         expr: subexpr.clone(),
131                         tries: sub_tries,
132                     });
133                     sub_tries = 0;
134                 }
135             }
136         }
137
138         Chain {
139             parent: children.pop().unwrap(),
140             children: children.into_iter().rev().collect(),
141         }
142     }
143 }
144
145 fn rewrite_chain_block(mut chain: Chain, context: &RewriteContext, shape: Shape) -> Option<String> {
146     let last = chain.children.pop().unwrap();
147
148     // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
149     let parent_rewrite = chain.parent.expr
150         .rewrite(context, shape)
151         .map(|parent_rw| parent_rw + &"?".repeat(chain.parent.tries))?;
152     let parent_rewrite_contains_newline = parent_rewrite.contains('\n');
153     let is_small_parent = shape.offset + parent_rewrite.len() <= context.config.tab_spaces();
154     let parent_is_block = is_block_expr(context, &chain.parent.expr, &parent_rewrite);
155
156     // Decide how to layout the rest of the chain. `extend` is true if we can
157     // put the first non-parent item on the same line as the parent.
158     let other_child_shape = if parent_is_block {
159         shape
160     } else {
161         shape.block_indent(context.config.tab_spaces())
162     }.with_max_width(context.config);
163
164     let extend = parent_is_block || (is_small_parent && !parent_rewrite_contains_newline && is_continuable(&chain.parent.expr));
165
166     let first_child_shape = if extend {
167         let offset = trimmed_last_line_width(&parent_rewrite) + chain.parent.tries;
168         other_child_shape.offset_left(offset)?
169     } else {
170         other_child_shape
171     };
172     debug!(
173         "child_shapes {:?} {:?}",
174         first_child_shape, other_child_shape
175     );
176
177     let mut rewrites: Vec<String> = Vec::with_capacity(chain.children.len());
178     let mut is_block_like = Vec::with_capacity(chain.children.len());
179     is_block_like.push(true);
180     for (i, item) in chain.children.iter().enumerate() {
181         let shape = if *is_block_like.last().unwrap() && !(extend && i == 0) {
182             first_child_shape
183         } else {
184             other_child_shape
185         };
186         let rewrite = rewrite_chain_subexpr(&item.expr, context, shape)?;
187         is_block_like.push(is_block_expr(context, &item.expr, &rewrite));
188         rewrites.push(format!("{}{}", rewrite, "?".repeat(item.tries)));
189     }
190
191     // Total of all items excluding the last.
192     let extend_last_subexpr = if is_small_parent {
193         rewrites.len() == 1 && last_line_extendable(&rewrites[0])
194     } else {
195         rewrites.is_empty() && last_line_extendable(&parent_rewrite)
196     };
197     let almost_total = if extend_last_subexpr {
198         last_line_width(&parent_rewrite)
199     } else {
200         rewrites.iter().fold(0, |a, b| a + b.len()) + parent_rewrite.len()
201     } + last.tries;
202     let one_line_budget = if rewrites.is_empty() {
203         shape.width
204     } else {
205         min(shape.width, context.config.width_heuristics().chain_width)
206     };
207     let all_in_one_line = !parent_rewrite_contains_newline
208         && rewrites.iter().all(|s| !s.contains('\n'))
209         && almost_total < one_line_budget;
210     let last_shape = if is_block_like[rewrites.len()] {
211         first_child_shape
212     } else {
213         other_child_shape
214     }.sub_width(shape.rhs_overhead(context.config) + last.tries)?;
215
216     // Rewrite the last child. The last child of a chain requires special treatment. We need to
217     // know whether 'overflowing' the last child make a better formatting:
218     //
219     // A chain with overflowing the last child:
220     // ```
221     // parent.child1.child2.last_child(
222     //     a,
223     //     b,
224     //     c,
225     // )
226     // ```
227     //
228     // A chain without overflowing the last child (in vertical layout):
229     // ```
230     // parent
231     //     .child1
232     //     .child2
233     //     .last_child(a, b, c)
234     // ```
235     //
236     // In particular, overflowing is effective when the last child is a method with a multi-lined
237     // block-like argument (e.g. closure):
238     // ```
239     // parent.child1.child2.last_child(|a, b, c| {
240     //     let x = foo(a, b, c);
241     //     let y = bar(a, b, c);
242     //
243     //     // ...
244     //
245     //     result
246     // })
247     // ```
248
249     // `rewrite_last` rewrites the last child on its own line. We use a closure here instead of
250     // directly calling `rewrite_chain_subexpr()` to avoid exponential blowup.
251     let (last_subexpr_str, fits_single_line) = if all_in_one_line || extend_last_subexpr {
252         // First we try to 'overflow' the last child and see if it looks better than using
253         // vertical layout.
254         shape.offset_left(almost_total).map(|shape| {
255             if let Some(rw) = rewrite_chain_subexpr(&last.expr, context, shape) {
256                 // We allow overflowing here only if both of the following conditions match:
257                 // 1. The entire chain fits in a single line except the last child.
258                 // 2. `last_child_str.lines().count() >= 5`.
259                 let line_count = rw.lines().count();
260                 let fits_single_line = almost_total + first_line_width(&rw) <= one_line_budget;
261                 if fits_single_line && line_count >= 5 {
262                     (Some(rw), true)
263                 } else {
264                     // We could not know whether overflowing is better than using vertical layout,
265                     // just by looking at the overflowed rewrite. Now we rewrite the last child
266                     // on its own line, and compare two rewrites to choose which is better.
267                     match rewrite_chain_subexpr(&last.expr, context, last_shape) {
268                         Some(ref new_rw) if !fits_single_line => (Some(new_rw.clone()), false),
269                         Some(ref new_rw) if new_rw.lines().count() >= line_count => {
270                             (Some(rw), fits_single_line)
271                         }
272                         new_rw @ Some(..) => (new_rw, false),
273                         _ => (Some(rw), fits_single_line),
274                     }
275                 }
276             } else {
277                 (rewrite_chain_subexpr(&last.expr, context, last_shape), false)
278             }
279         })?
280     } else {
281         (rewrite_chain_subexpr(&last.expr, context, last_shape), false)
282     };
283     rewrites.push(last_subexpr_str?);
284     // We should never look at this, since we only look at the block-ness of the
285     // previous item in the chain.
286     is_block_like.push(false);
287
288     let connector = if fits_single_line && !parent_rewrite_contains_newline {
289         // Yay, we can put everything on one line.
290         Cow::from("")
291     } else {
292         // Use new lines.
293         if *context.force_one_line_chain.borrow() {
294             return None;
295         }
296         other_child_shape.indent.to_string_with_newline(context.config)
297     };
298
299     let first_connector = if is_small_parent
300         || fits_single_line
301         || last_line_extendable(&parent_rewrite)
302     {
303         ""
304     } else {
305         &connector
306     };
307
308     let result = if is_small_parent && rewrites.len() > 1 {
309         let second_connector = if fits_single_line
310             || rewrites[1] == "?"
311             || last_line_extendable(&rewrites[0])
312         {
313             ""
314         } else {
315             &connector
316         };
317         format!(
318             "{}{}{}{}{}",
319             parent_rewrite,
320             first_connector,
321             rewrites[0],
322             second_connector,
323             join_rewrites(&rewrites[1..], &is_block_like[2..], &connector),
324         )
325     } else {
326         format!(
327             "{}{}{}",
328             parent_rewrite,
329             first_connector,
330             join_rewrites(&rewrites, &is_block_like[1..], &connector),
331         )
332     };
333     let result = format!("{}{}", result, "?".repeat(last.tries));
334     Some(result)
335 }
336
337 fn rewrite_chain_visual(mut chain: Chain, context: &RewriteContext, shape: Shape) -> Option<String> {
338     let last = chain.children.pop().unwrap();
339
340     // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
341     let parent_shape = if is_block_expr(context, &chain.parent.expr, "\n") {
342         shape.visual_indent(0)
343     } else {
344         shape
345     };
346     let parent_rewrite = chain.parent.expr
347         .rewrite(context, parent_shape)
348         .map(|parent_rw| parent_rw + &"?".repeat(chain.parent.tries))?;
349     let parent_rewrite_contains_newline = parent_rewrite.contains('\n');
350
351     let other_child_shape = shape.visual_indent(0).with_max_width(context.config);
352
353     // Decide how to layout the rest of the chain. `extend` is true if we can
354     // put the first non-parent item on the same line as the parent.
355     let extend = !parent_rewrite_contains_newline && is_continuable(&chain.parent.expr);
356
357     let first_child_shape = if extend {
358         let overhead = last_line_width(&parent_rewrite);
359         parent_shape.offset_left(overhead)?
360     } else {
361         other_child_shape
362     };
363     debug!(
364         "child_shapes {:?} {:?}",
365         first_child_shape, other_child_shape
366     );
367
368     let mut rewrites: Vec<String> = Vec::with_capacity(chain.children.len());
369     for (i, item) in chain.children.iter().enumerate() {
370         let shape = if i == 0 {
371             first_child_shape
372         } else {
373             other_child_shape
374         };
375         let rewrite = rewrite_chain_subexpr(&item.expr, context, shape)?;
376         rewrites.push(format!("{}{}", rewrite, "?".repeat(item.tries)));
377     }
378
379     // Total of all items excluding the last.
380     let almost_total = rewrites.iter().fold(0, |a, b| a + b.len()) + parent_rewrite.len() + last.tries;
381     let one_line_budget = if rewrites.is_empty() {
382         shape.width
383     } else {
384         min(shape.width, context.config.width_heuristics().chain_width)
385     };
386     let all_in_one_line = !parent_rewrite_contains_newline
387         && rewrites.iter().all(|s| !s.contains('\n'))
388         && almost_total < one_line_budget;
389     let last_shape =
390         other_child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?;
391
392     // Rewrite the last child. The last child of a chain requires special treatment. We need to
393     // know whether 'overflowing' the last child make a better formatting:
394     //
395     // A chain with overflowing the last child:
396     // ```
397     // parent.child1.child2.last_child(
398     //     a,
399     //     b,
400     //     c,
401     // )
402     // ```
403     //
404     // A chain without overflowing the last child (in vertical layout):
405     // ```
406     // parent
407     //     .child1
408     //     .child2
409     //     .last_child(a, b, c)
410     // ```
411     //
412     // In particular, overflowing is effective when the last child is a method with a multi-lined
413     // block-like argument (e.g. closure):
414     // ```
415     // parent.child1.child2.last_child(|a, b, c| {
416     //     let x = foo(a, b, c);
417     //     let y = bar(a, b, c);
418     //
419     //     // ...
420     //
421     //     result
422     // })
423     // ```
424
425     let mut last_subexpr_str = None;
426     let mut fits_single_line = false;
427
428     if all_in_one_line {
429         // First we try to 'overflow' the last child and see if it looks better than using
430         // vertical layout.
431         if let Some(shape) = parent_shape.offset_left(almost_total) {
432             if let Some(rw) = rewrite_chain_subexpr(&last.expr, context, shape) {
433                 // We allow overflowing here only if both of the following conditions match:
434                 // 1. The entire chain fits in a single line except the last child.
435                 // 2. `last_child_str.lines().count() >= 5`.
436                 let line_count = rw.lines().count();
437                 let could_fit_single_line = almost_total + first_line_width(&rw) <= one_line_budget;
438                 if could_fit_single_line && line_count >= 5 {
439                     last_subexpr_str = Some(rw);
440                     fits_single_line = true;
441                 } else {
442                     // We could not know whether overflowing is better than using vertical layout,
443                     // just by looking at the overflowed rewrite. Now we rewrite the last child
444                     // on its own line, and compare two rewrites to choose which is better.
445                     match rewrite_chain_subexpr(&last.expr, context, last_shape) {
446                         Some(ref new_rw) if !could_fit_single_line => {
447                             last_subexpr_str = Some(new_rw.clone());
448                         }
449                         Some(ref new_rw) if new_rw.lines().count() >= line_count => {
450                             last_subexpr_str = Some(rw);
451                             fits_single_line = could_fit_single_line;
452                         }
453                         new_rw @ Some(..) => {
454                             last_subexpr_str = new_rw;
455                         }
456                         _ => {
457                             last_subexpr_str = Some(rw);
458                             fits_single_line = could_fit_single_line;
459                         }
460                     }
461                 }
462             }
463         }
464     } 
465
466     last_subexpr_str = last_subexpr_str.or_else(|| rewrite_chain_subexpr(&last.expr, context, last_shape));
467     rewrites.push(last_subexpr_str?);
468
469     let connector = if fits_single_line && !parent_rewrite_contains_newline {
470         // Yay, we can put everything on one line.
471         Cow::from("")
472     } else {
473         // Use new lines.
474         if *context.force_one_line_chain.borrow() {
475             return None;
476         }
477         other_child_shape.indent.to_string_with_newline(context.config)
478     };
479
480     let result = format!("{}{}{}",
481         parent_rewrite,
482         join_rewrites_vis(&rewrites, &connector),
483         "?".repeat(last.tries),
484     );
485     wrap_str(result, context.config.max_width(), shape)
486 }
487
488 fn join_rewrites(rewrites: &[String], is_block_like: &[bool], connector: &str) -> String {
489     let mut rewrite_iter = rewrites.iter();
490     let mut result = rewrite_iter.next().unwrap().clone();
491
492     for (rewrite, prev_is_block_like) in rewrite_iter.zip(is_block_like.iter()) {
493         if rewrite != "?" && !prev_is_block_like {
494             result.push_str(connector);
495         }
496         result.push_str(&rewrite);
497     }
498
499     result
500 }
501
502 fn join_rewrites_vis(rewrites: &[String], connector: &str) -> String {
503     let mut rewrite_iter = rewrites.iter();
504     let mut result = rewrite_iter.next().unwrap().clone();
505
506     for rewrite in rewrite_iter {
507         if rewrite != "?" {
508             result.push_str(connector);
509         }
510         result.push_str(&rewrite);
511     }
512
513     result
514 }
515
516 // States whether an expression's last line exclusively consists of closing
517 // parens, braces, and brackets in its idiomatic formatting.
518 fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
519     match expr.node {
520         ast::ExprKind::Mac(..) | ast::ExprKind::Call(..) => {
521             context.use_block_indent() && repr.contains('\n')
522         }
523         ast::ExprKind::Struct(..)
524         | ast::ExprKind::While(..)
525         | ast::ExprKind::WhileLet(..)
526         | ast::ExprKind::If(..)
527         | ast::ExprKind::IfLet(..)
528         | ast::ExprKind::Block(..)
529         | ast::ExprKind::Loop(..)
530         | ast::ExprKind::ForLoop(..)
531         | ast::ExprKind::Match(..) => repr.contains('\n'),
532         ast::ExprKind::Paren(ref expr)
533         | ast::ExprKind::Binary(_, _, ref expr)
534         | ast::ExprKind::Index(_, ref expr)
535         | ast::ExprKind::Unary(_, ref expr)
536         | ast::ExprKind::Closure(_, _, _, _, ref expr, _) => is_block_expr(context, expr, repr),
537         ast::ExprKind::MethodCall(_, ref exprs) => {
538             // TODO maybe should be like Call
539             is_block_expr(context, exprs.last().unwrap(), repr)
540         }
541         _ => false,
542     }
543 }
544
545 // Returns a Vec of the prefixes of the chain.
546 // E.g., for input `a.b.c` we return [`a.b.c`, `a.b`, 'a']
547 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext) -> Vec<ast::Expr> {
548     let mut subexpr_list = vec![expr.clone()];
549
550     while let Some(subexpr) = pop_expr_chain(subexpr_list.last().unwrap(), context) {
551         subexpr_list.push(subexpr.clone());
552     }
553
554     subexpr_list
555 }
556
557 // Returns the expression's subexpression, if it exists. When the subexpr
558 // is a try! macro, we'll convert it to shorthand when the option is set.
559 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext) -> Option<ast::Expr> {
560     match expr.node {
561         ast::ExprKind::MethodCall(_, ref expressions) => {
562             Some(convert_try(&expressions[0], context))
563         }
564         ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) => {
565             Some(convert_try(subexpr, context))
566         }
567         _ => None,
568     }
569 }
570
571 fn convert_try(expr: &ast::Expr, context: &RewriteContext) -> ast::Expr {
572     match expr.node {
573         ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
574             if let Some(subexpr) = convert_try_mac(mac, context) {
575                 subexpr
576             } else {
577                 expr.clone()
578             }
579         }
580         _ => expr.clone(),
581     }
582 }
583
584 // Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
585 // `.c`.
586 fn rewrite_chain_subexpr(
587     expr: &ast::Expr,
588     context: &RewriteContext,
589     shape: Shape,
590 ) -> Option<String> {
591     let rewrite_element = |expr_str: String| {
592         if expr_str.len() <= shape.width {
593             Some(expr_str)
594         } else {
595             None
596         }
597     };
598
599     match expr.node {
600         ast::ExprKind::MethodCall(ref segment, ref expressions) => {
601             let types = match segment.args {
602                 Some(ref params) => match **params {
603                     ast::GenericArgs::AngleBracketed(ref data) => &data.args[..],
604                     _ => &[],
605                 },
606                 _ => &[],
607             };
608             rewrite_method_call(segment.ident, types, expressions, expr.span, context, shape)
609         }
610         ast::ExprKind::Field(ref nested, ref field) => {
611             let space = if is_tup_field_access(expr) && is_tup_field_access(nested) {
612                 " "
613             } else {
614                 ""
615             };
616             rewrite_element(format!("{}.{}", space, field.name))
617         }
618         ast::ExprKind::Try(_) => rewrite_element(String::from("?")),
619         _ => unreachable!(),
620     }
621 }
622
623 fn is_tup_field_access(expr: &ast::Expr) -> bool {
624     match expr.node {
625         ast::ExprKind::Field(_, ref field) => {
626             field.name.to_string().chars().all(|c| c.is_digit(10))
627         }
628         _ => false,
629     }
630 }
631
632 // Determines if we can continue formatting a given expression on the same line.
633 fn is_continuable(expr: &ast::Expr) -> bool {
634     match expr.node {
635         ast::ExprKind::Path(..) => true,
636         _ => false,
637     }
638 }
639
640 fn rewrite_method_call(
641     method_name: ast::Ident,
642     types: &[ast::GenericArg],
643     args: &[ptr::P<ast::Expr>],
644     span: Span,
645     context: &RewriteContext,
646     shape: Shape,
647 ) -> Option<String> {
648     let (lo, type_str) = if types.is_empty() {
649         (args[0].span.hi(), String::new())
650     } else {
651         let type_list = types
652             .iter()
653             .map(|ty| ty.rewrite(context, shape))
654             .collect::<Option<Vec<_>>>()?;
655
656         let type_str = format!("::<{}>", type_list.join(", "));
657
658         (types.last().unwrap().span().hi(), type_str)
659     };
660
661     let callee_str = format!(".{}{}", method_name, type_str);
662     let span = mk_sp(lo, span.hi());
663
664     rewrite_call(context, &callee_str, &args[1..], span, shape)
665 }