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