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