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