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