Skip to main content

rustfmt_nightly/
chains.rs

1//! Formatting of chained expressions, i.e., expressions that are chained by
2//! dots: struct and enum field access, method calls, and try shorthand (`?`).
3//!
4//! Instead of walking these subexpressions one-by-one, as is our usual strategy
5//! for expression formatting, we collect maximal sequences of these expressions
6//! and handle them simultaneously.
7//!
8//! Whenever possible, the entire chain is put on a single line. If that fails,
9//! we put each subexpression on a separate, much like the (default) function
10//! argument function argument strategy.
11//!
12//! Depends on config options: `chain_indent` is the indent to use for
13//! blocks in the parent/root/base of the chain (and the rest of the chain's
14//! alignment).
15//! E.g., `let foo = { aaaa; bbb; ccc }.bar.baz();`, we would layout for the
16//! following values of `chain_indent`:
17//! Block:
18//!
19//! ```text
20//! let foo = {
21//!     aaaa;
22//!     bbb;
23//!     ccc
24//! }.bar
25//!     .baz();
26//! ```
27//!
28//! Visual:
29//!
30//! ```text
31//! let foo = {
32//!               aaaa;
33//!               bbb;
34//!               ccc
35//!           }
36//!           .bar
37//!           .baz();
38//! ```
39//!
40//! If the first item in the chain is a block expression, we align the dots with
41//! the braces.
42//! Block:
43//!
44//! ```text
45//! let a = foo.bar
46//!     .baz()
47//!     .qux
48//! ```
49//!
50//! Visual:
51//!
52//! ```text
53//! let a = foo.bar
54//!            .baz()
55//!            .qux
56//! ```
57
58use std::borrow::Cow;
59use std::cmp::min;
60
61use rustc_ast::ast;
62use rustc_span::{BytePos, Span, symbol};
63use tracing::debug;
64
65use crate::comment::{CharClasses, FullCodeCharKind, RichChar, rewrite_comment};
66use crate::config::{IndentStyle, StyleEdition};
67use crate::expr::rewrite_call;
68use crate::lists::extract_pre_comment;
69use crate::macros::convert_try_mac;
70use crate::rewrite::{
71    ExceedsMaxWidthError, Rewrite, RewriteContext, RewriteError, RewriteErrorExt, RewriteResult,
72};
73use crate::shape::Shape;
74use crate::source_map::SpanUtils;
75use crate::utils::{
76    self, filtered_str_fits, first_line_width, last_line_extendable, last_line_width, mk_sp,
77    rewrite_ident, trimmed_last_line_width, wrap_str,
78};
79
80use thin_vec::ThinVec;
81
82/// Provides the original input contents from the span
83/// of a chain element with trailing spaces trimmed.
84fn format_overflow_style(span: Span, context: &RewriteContext<'_>) -> Option<String> {
85    // TODO(ding-young): Currently returning None when the given span is out of the range
86    // covered by the snippet provider. If this is a common cause for internal
87    // rewrite failure, add a new enum variant and return RewriteError instead of None
88    context.snippet_provider.span_to_snippet(span).map(|s| {
89        s.lines()
90            .map(|l| l.trim_end())
91            .collect::<Vec<_>>()
92            .join("\n")
93    })
94}
95
96fn format_chain_item(
97    item: &ChainItem,
98    context: &RewriteContext<'_>,
99    rewrite_shape: Shape,
100    allow_overflow: bool,
101) -> RewriteResult {
102    if allow_overflow {
103        // TODO(ding-young): Consider calling format_overflow_style()
104        // only when item.rewrite_result() returns RewriteError::ExceedsMaxWidth.
105        // It may be inappropriate to call format_overflow_style on other RewriteError
106        // since the current approach retries formatting if allow_overflow is true
107        item.rewrite_result(context, rewrite_shape)
108            .or_else(|_| format_overflow_style(item.span, context).unknown_error())
109    } else {
110        item.rewrite_result(context, rewrite_shape)
111    }
112}
113
114fn get_block_child_shape(
115    prev_ends_with_block: bool,
116    context: &RewriteContext<'_>,
117    shape: Shape,
118) -> Shape {
119    if prev_ends_with_block {
120        shape.block_indent(0)
121    } else {
122        shape.block_indent(context.config.tab_spaces())
123    }
124    .with_max_width(context.config)
125}
126
127fn get_visual_style_child_shape(
128    context: &RewriteContext<'_>,
129    shape: Shape,
130    offset: usize,
131    parent_overflowing: bool,
132    span: Span,
133) -> Result<Shape, ExceedsMaxWidthError> {
134    if !parent_overflowing {
135        shape
136            .with_max_width(context.config)
137            .offset_left(offset, span)
138            .map(|s| s.visual_indent(0))
139    } else {
140        Ok(shape.visual_indent(offset))
141    }
142}
143
144pub(crate) fn rewrite_chain(
145    expr: &ast::Expr,
146    context: &RewriteContext<'_>,
147    shape: Shape,
148) -> RewriteResult {
149    let chain = Chain::from_ast(expr, context);
150    debug!("rewrite_chain {:?} {:?}", chain, shape);
151
152    // If this is just an expression with some `?`s, then format it trivially and
153    // return early.
154    if chain.children.is_empty() {
155        return chain.parent.rewrite_result(context, shape);
156    }
157
158    chain.rewrite_result(context, shape)
159}
160
161#[derive(Debug)]
162enum CommentPosition {
163    SameLine,
164    DifferentLine,
165}
166
167/// Information about an expression in a chain.
168struct SubExpr {
169    expr: ast::Expr,
170    is_postfix_receiver: bool,
171}
172
173/// An expression plus trailing `?`s to be formatted together.
174#[derive(Debug)]
175struct ChainItem {
176    kind: ChainItemKind,
177    tries: usize,
178    // The entire span of the chain item, including the leading dot and any comments, e.g.
179    // `.some_method(arg, arg)`, or  `. /* a comment */ my_attribute`.
180    span: Span,
181}
182
183// FIXME: we can't use a reference here because to convert `try!` to `?` we
184// synthesise the AST node. However, I think we could use `Cow` and that
185// would remove a lot of cloning.
186#[derive(Debug)]
187enum ChainItemKind {
188    Parent {
189        expr: ast::Expr,
190        parens: bool,
191    },
192    MethodCall(
193        ast::PathSegment,
194        Vec<ast::GenericArg>,
195        ThinVec<Box<ast::Expr>>,
196    ),
197    StructField(symbol::Ident),
198    /// Tuple field access like `foo.1`.
199    TupleField {
200        field: symbol::Ident,
201        /// Whether this is a nested tuple access, like `.2` in `foo.1.2`.
202        is_nested: bool,
203    },
204    Await,
205    Use,
206    Yield,
207    /// A comment within a chain, e.g. `parent. item /* comment */.rest`.
208    Comment(String, CommentPosition),
209}
210
211impl ChainItemKind {
212    fn is_block_like(&self, context: &RewriteContext<'_>, reps: &str) -> bool {
213        match self {
214            ChainItemKind::Parent { expr, .. } => utils::is_block_expr(context, expr, reps),
215            ChainItemKind::MethodCall(..)
216            | ChainItemKind::StructField(..)
217            | ChainItemKind::TupleField { .. }
218            | ChainItemKind::Await
219            | ChainItemKind::Use
220            | ChainItemKind::Yield
221            | ChainItemKind::Comment(..) => false,
222        }
223    }
224
225    fn is_tup_field_access_expr(expr: &ast::Expr) -> bool {
226        match &expr.kind {
227            ast::ExprKind::Field(_, right) => Self::is_tup_field_ident(right),
228            _ => false,
229        }
230    }
231
232    fn is_tup_field_ident(field: &symbol::Ident) -> bool {
233        field.name.as_str().chars().all(|c| c.is_ascii_digit())
234    }
235
236    fn from_ast(
237        context: &RewriteContext<'_>,
238        expr: &ast::Expr,
239        is_postfix_receiver: bool,
240    ) -> (ChainItemKind, Span) {
241        let (kind, span) = match &expr.kind {
242            ast::ExprKind::MethodCall(call) => {
243                let types = match call.seg.args.as_deref() {
244                    Some(ast::GenericArgs::AngleBracketed(data)) => data
245                        .args
246                        .iter()
247                        .filter_map(|x| match x {
248                            ast::AngleBracketedArg::Arg(generic_arg) => Some(generic_arg.clone()),
249                            _ => None,
250                        })
251                        .collect::<Vec<_>>(),
252                    _ => vec![],
253                };
254                let span = mk_sp(call.receiver.span.hi(), expr.span.hi());
255                let kind = ChainItemKind::MethodCall(call.seg.clone(), types, call.args.clone());
256                (kind, span)
257            }
258            ast::ExprKind::Field(nested, field) => {
259                let kind = if Self::is_tup_field_ident(field) {
260                    ChainItemKind::TupleField {
261                        field: *field,
262                        is_nested: Self::is_tup_field_access_expr(nested),
263                    }
264                } else {
265                    ChainItemKind::StructField(*field)
266                };
267                let span = mk_sp(nested.span.hi(), field.span.hi());
268                (kind, span)
269            }
270            ast::ExprKind::Await(nested, _) => {
271                let span = mk_sp(nested.span.hi(), expr.span.hi());
272                (ChainItemKind::Await, span)
273            }
274            ast::ExprKind::Use(nested, _) => {
275                let span = mk_sp(nested.span.hi(), expr.span.hi());
276                (ChainItemKind::Use, span)
277            }
278            ast::ExprKind::Yield(ast::YieldKind::Postfix(nested)) => {
279                let span = mk_sp(nested.span.hi(), expr.span.hi());
280                (ChainItemKind::Yield, span)
281            }
282            _ => {
283                return (
284                    ChainItemKind::Parent {
285                        expr: expr.clone(),
286                        parens: is_postfix_receiver && should_add_parens(expr, context),
287                    },
288                    expr.span,
289                );
290            }
291        };
292
293        // Remove comments from the span.
294        let lo = context.snippet_provider.span_before(span, ".");
295        (kind, mk_sp(lo, span.hi()))
296    }
297}
298
299impl Rewrite for ChainItem {
300    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
301        self.rewrite_result(context, shape).ok()
302    }
303
304    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
305        let shape = shape.sub_width(self.tries, self.span)?;
306        let rewrite = match self.kind {
307            ChainItemKind::Parent {
308                ref expr,
309                parens: true,
310            } => crate::expr::rewrite_paren(context, &expr, shape, expr.span)?,
311            ChainItemKind::Parent {
312                ref expr,
313                parens: false,
314            } => expr.rewrite_result(context, shape)?,
315            ChainItemKind::MethodCall(ref segment, ref types, ref exprs) => {
316                Self::rewrite_method_call(segment.ident, types, exprs, self.span, context, shape)?
317            }
318            ChainItemKind::StructField(ident) => format!(".{}", rewrite_ident(context, ident)),
319            ChainItemKind::TupleField { field, is_nested } => format!(
320                "{}.{}",
321                if is_nested && context.config.style_edition() <= StyleEdition::Edition2021 {
322                    " "
323                } else {
324                    ""
325                },
326                rewrite_ident(context, field)
327            ),
328            ChainItemKind::Await => ".await".to_owned(),
329            ChainItemKind::Use => ".use".to_owned(),
330            ChainItemKind::Yield => ".yield".to_owned(),
331            ChainItemKind::Comment(ref comment, _) => {
332                rewrite_comment(comment, false, shape, context.config)?
333            }
334        };
335        Ok(format!("{rewrite}{}", "?".repeat(self.tries)))
336    }
337}
338
339impl ChainItem {
340    fn new(context: &RewriteContext<'_>, expr: &SubExpr, tries: usize) -> ChainItem {
341        let (kind, span) = ChainItemKind::from_ast(context, &expr.expr, expr.is_postfix_receiver);
342        ChainItem { kind, tries, span }
343    }
344
345    fn comment(span: Span, comment: String, pos: CommentPosition) -> ChainItem {
346        ChainItem {
347            kind: ChainItemKind::Comment(comment, pos),
348            tries: 0,
349            span,
350        }
351    }
352
353    fn is_comment(&self) -> bool {
354        matches!(self.kind, ChainItemKind::Comment(..))
355    }
356
357    fn rewrite_method_call(
358        method_name: symbol::Ident,
359        types: &[ast::GenericArg],
360        args: &[Box<ast::Expr>],
361        span: Span,
362        context: &RewriteContext<'_>,
363        shape: Shape,
364    ) -> RewriteResult {
365        let type_str = if types.is_empty() {
366            String::new()
367        } else {
368            let type_list = types
369                .iter()
370                .map(|ty| ty.rewrite_result(context, shape))
371                .collect::<Result<Vec<_>, RewriteError>>()?;
372
373            format!("::<{}>", type_list.join(", "))
374        };
375        let callee_str = format!(".{}{}", rewrite_ident(context, method_name), type_str);
376        rewrite_call(context, &callee_str, &args, span, shape)
377    }
378}
379
380#[derive(Debug)]
381struct Chain {
382    parent: ChainItem,
383    children: Vec<ChainItem>,
384}
385
386impl Chain {
387    fn from_ast(expr: &ast::Expr, context: &RewriteContext<'_>) -> Chain {
388        let subexpr_list = Self::make_subexpr_list(expr, context);
389
390        // Un-parse the expression tree into ChainItems
391        let mut rev_children = vec![];
392        let mut sub_tries = 0;
393        for subexpr in &subexpr_list {
394            match subexpr.expr.kind {
395                ast::ExprKind::Try(_) => sub_tries += 1,
396                _ => {
397                    rev_children.push(ChainItem::new(context, subexpr, sub_tries));
398                    sub_tries = 0;
399                }
400            }
401        }
402
403        fn is_tries(s: &str) -> bool {
404            s.chars().all(|c| c == '?')
405        }
406
407        fn is_post_comment(s: &str) -> bool {
408            let comment_start_index = s.chars().position(|c| c == '/');
409            if comment_start_index.is_none() {
410                return false;
411            }
412
413            let newline_index = s.chars().position(|c| c == '\n');
414            if newline_index.is_none() {
415                return true;
416            }
417
418            comment_start_index.unwrap() < newline_index.unwrap()
419        }
420
421        fn handle_post_comment(
422            post_comment_span: Span,
423            post_comment_snippet: &str,
424            prev_span_end: &mut BytePos,
425            children: &mut Vec<ChainItem>,
426        ) {
427            let white_spaces = &[' ', '\t'];
428            if post_comment_snippet
429                .trim_matches(white_spaces)
430                .starts_with('\n')
431            {
432                // No post comment.
433                return;
434            }
435            let trimmed_snippet = trim_tries(post_comment_snippet);
436            if is_post_comment(&trimmed_snippet) {
437                children.push(ChainItem::comment(
438                    post_comment_span,
439                    trimmed_snippet.trim().to_owned(),
440                    CommentPosition::SameLine,
441                ));
442                *prev_span_end = post_comment_span.hi();
443            }
444        }
445
446        let parent = rev_children.pop().unwrap();
447        let mut children = vec![];
448        let mut prev_span_end = parent.span.hi();
449        let mut iter = rev_children.into_iter().rev().peekable();
450        if let Some(first_chain_item) = iter.peek() {
451            // `parent? /* maybe comment */ . /* maybe comment */ first_child`
452            //        ^------------------- ^ comment_span
453            let comment_span = mk_sp(prev_span_end, first_chain_item.span.lo());
454            let comment_snippet = context.snippet(comment_span);
455            if !is_tries(comment_snippet.trim()) {
456                handle_post_comment(
457                    comment_span,
458                    comment_snippet,
459                    &mut prev_span_end,
460                    &mut children,
461                );
462            }
463        }
464        while let Some(chain_item) = iter.next() {
465            let comment_snippet = context.snippet(chain_item.span);
466            let handle_comment = !is_tries(comment_snippet.trim());
467
468            // Pre-comment
469            if handle_comment {
470                let pre_comment_span = mk_sp(prev_span_end, chain_item.span.lo());
471                let pre_comment_snippet = trim_tries(context.snippet(pre_comment_span));
472                if let (Some(pre_comment), _) = extract_pre_comment(&pre_comment_snippet) {
473                    if !pre_comment.is_empty() {
474                        children.push(ChainItem::comment(
475                            pre_comment_span,
476                            pre_comment.to_owned(),
477                            CommentPosition::DifferentLine,
478                        ));
479                    }
480                }
481            }
482
483            prev_span_end = chain_item.span.hi();
484            children.push(chain_item);
485
486            // Post-comment
487            if !handle_comment || iter.peek().is_none() {
488                continue;
489            }
490
491            let next_lo = iter.peek().unwrap().span.lo();
492            let post_comment_span = mk_sp(prev_span_end, next_lo);
493            let post_comment_snippet = context.snippet(post_comment_span);
494            handle_post_comment(
495                post_comment_span,
496                post_comment_snippet,
497                &mut prev_span_end,
498                &mut children,
499            );
500        }
501
502        Chain { parent, children }
503    }
504
505    // Returns a Vec of the prefixes of the chain.
506    // E.g., for input `a.b.c` we return [`a.b.c`, `a.b`, 'a']
507    fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext<'_>) -> Vec<SubExpr> {
508        let mut subexpr_list = vec![SubExpr {
509            expr: expr.clone(),
510            is_postfix_receiver: false,
511        }];
512
513        while let Some(subexpr) = Self::pop_expr_chain(&subexpr_list.last().unwrap().expr, context)
514        {
515            subexpr_list.push(subexpr);
516        }
517
518        subexpr_list
519    }
520
521    // Returns the expression's subexpression, if it exists. When the subexpr
522    // is a try! macro, we'll convert it to shorthand when the option is set.
523    fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext<'_>) -> Option<SubExpr> {
524        match &expr.kind {
525            ast::ExprKind::MethodCall(call) => Some(SubExpr {
526                expr: Self::convert_try(&call.receiver, context),
527                is_postfix_receiver: true,
528            }),
529            ast::ExprKind::Field(subexpr, _)
530            | ast::ExprKind::Await(subexpr, _)
531            | ast::ExprKind::Use(subexpr, _)
532            | ast::ExprKind::Yield(ast::YieldKind::Postfix(subexpr)) => Some(SubExpr {
533                expr: Self::convert_try(subexpr, context),
534                is_postfix_receiver: true,
535            }),
536            ast::ExprKind::Try(subexpr) => Some(SubExpr {
537                expr: Self::convert_try(subexpr, context),
538                is_postfix_receiver: false,
539            }),
540            _ => None,
541        }
542    }
543
544    fn convert_try(expr: &ast::Expr, context: &RewriteContext<'_>) -> ast::Expr {
545        match &expr.kind {
546            ast::ExprKind::MacCall(mac) if context.config.use_try_shorthand() => {
547                convert_try_mac(mac, context).unwrap_or(expr.clone())
548            }
549            _ => expr.clone(),
550        }
551    }
552}
553
554impl Rewrite for Chain {
555    fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
556        self.rewrite_result(context, shape).ok()
557    }
558
559    fn rewrite_result(&self, context: &RewriteContext<'_>, shape: Shape) -> RewriteResult {
560        debug!("rewrite chain {:?} {:?}", self, shape);
561
562        let mut formatter = match context.config.indent_style() {
563            IndentStyle::Block => {
564                Box::new(ChainFormatterBlock::new(self)) as Box<dyn ChainFormatter>
565            }
566            IndentStyle::Visual => {
567                Box::new(ChainFormatterVisual::new(self)) as Box<dyn ChainFormatter>
568            }
569        };
570
571        formatter.format_root(&self.parent, context, shape)?;
572        if let Some(result) = formatter.pure_root() {
573            return wrap_str(
574                result,
575                context.config.max_width(),
576                context.config.tab_spaces(),
577                shape,
578            )
579            .max_width_error(shape.width, self.parent.span);
580        }
581
582        let first = self.children.first().unwrap_or(&self.parent);
583        let last = self.children.last().unwrap_or(&self.parent);
584        let children_span = mk_sp(first.span.lo(), last.span.hi());
585        let full_span = self.parent.span.with_hi(children_span.hi());
586
587        // Decide how to layout the rest of the chain.
588        let child_shape = formatter.child_shape(context, shape, children_span)?;
589
590        formatter.format_children(context, child_shape)?;
591        formatter.format_last_child(context, shape, child_shape)?;
592
593        let result = formatter.join_rewrites(context, child_shape)?;
594        wrap_str(
595            result,
596            context.config.max_width(),
597            context.config.tab_spaces(),
598            shape,
599        )
600        .max_width_error(shape.width, full_span)
601    }
602}
603
604// There are a few types for formatting chains. This is because there is a lot
605// in common between formatting with block vs visual indent, but they are
606// different enough that branching on the indent all over the place gets ugly.
607// Anything that can format a chain is a ChainFormatter.
608trait ChainFormatter {
609    // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
610    // Root is the parent plus any other chain items placed on the first line to
611    // avoid an orphan. E.g.,
612    // ```text
613    // foo.bar
614    //     .baz()
615    // ```
616    // If `bar` were not part of the root, then foo would be orphaned and 'float'.
617    fn format_root(
618        &mut self,
619        parent: &ChainItem,
620        context: &RewriteContext<'_>,
621        shape: Shape,
622    ) -> Result<(), RewriteError>;
623    fn child_shape(
624        &self,
625        context: &RewriteContext<'_>,
626        shape: Shape,
627        span: Span,
628    ) -> Result<Shape, ExceedsMaxWidthError>;
629    fn format_children(
630        &mut self,
631        context: &RewriteContext<'_>,
632        child_shape: Shape,
633    ) -> Result<(), RewriteError>;
634    fn format_last_child(
635        &mut self,
636        context: &RewriteContext<'_>,
637        shape: Shape,
638        child_shape: Shape,
639    ) -> Result<(), RewriteError>;
640    fn join_rewrites(&self, context: &RewriteContext<'_>, child_shape: Shape) -> RewriteResult;
641    // Returns `Some` if the chain is only a root, None otherwise.
642    fn pure_root(&mut self) -> Option<String>;
643}
644
645// Data and behaviour that is shared by both chain formatters. The concrete
646// formatters can delegate much behaviour to `ChainFormatterShared`.
647struct ChainFormatterShared<'a> {
648    // The current working set of child items.
649    children: &'a [ChainItem],
650    // The current rewrites of items (includes trailing `?`s, but not any way to
651    // connect the rewrites together).
652    rewrites: Vec<String>,
653    // Whether the chain can fit on one line.
654    fits_single_line: bool,
655    // The number of children in the chain. This is not equal to `self.children.len()`
656    // because `self.children` will change size as we process the chain.
657    child_count: usize,
658    // Whether elements are allowed to overflow past the max_width limit
659    allow_overflow: bool,
660}
661
662impl<'a> ChainFormatterShared<'a> {
663    fn new(chain: &'a Chain) -> ChainFormatterShared<'a> {
664        ChainFormatterShared {
665            children: &chain.children,
666            rewrites: Vec::with_capacity(chain.children.len() + 1),
667            fits_single_line: false,
668            child_count: chain.children.len(),
669            // TODO(calebcartwright)
670            allow_overflow: false,
671        }
672    }
673
674    fn pure_root(&mut self) -> Option<String> {
675        if self.children.is_empty() {
676            assert_eq!(self.rewrites.len(), 1);
677            Some(self.rewrites.pop().unwrap())
678        } else {
679            None
680        }
681    }
682
683    fn format_children(
684        &mut self,
685        context: &RewriteContext<'_>,
686        child_shape: Shape,
687    ) -> Result<(), RewriteError> {
688        for item in &self.children[..self.children.len() - 1] {
689            let rewrite = format_chain_item(item, context, child_shape, self.allow_overflow)?;
690            self.rewrites.push(rewrite);
691        }
692        Ok(())
693    }
694
695    // Rewrite the last child. The last child of a chain requires special treatment. We need to
696    // know whether 'overflowing' the last child make a better formatting:
697    //
698    // A chain with overflowing the last child:
699    // ```text
700    // parent.child1.child2.last_child(
701    //     a,
702    //     b,
703    //     c,
704    // )
705    // ```
706    //
707    // A chain without overflowing the last child (in vertical layout):
708    // ```text
709    // parent
710    //     .child1
711    //     .child2
712    //     .last_child(a, b, c)
713    // ```
714    //
715    // In particular, overflowing is effective when the last child is a method with a multi-lined
716    // block-like argument (e.g., closure):
717    // ```text
718    // parent.child1.child2.last_child(|a, b, c| {
719    //     let x = foo(a, b, c);
720    //     let y = bar(a, b, c);
721    //
722    //     // ...
723    //
724    //     result
725    // })
726    // ```
727    fn format_last_child(
728        &mut self,
729        may_extend: bool,
730        context: &RewriteContext<'_>,
731        shape: Shape,
732        child_shape: Shape,
733    ) -> Result<(), RewriteError> {
734        let last = self.children.last().unknown_error()?;
735        let extendable = may_extend && last_line_extendable(&self.rewrites[0]);
736        let prev_last_line_width = last_line_width(&self.rewrites[0], context.config.tab_spaces());
737
738        // Total of all items excluding the last.
739        let almost_total = if extendable {
740            prev_last_line_width
741        } else {
742            self.rewrites
743                .iter()
744                .map(|rw| utils::unicode_str_width(rw))
745                .sum()
746        } + last.tries;
747        let one_line_budget = if self.child_count == 1 {
748            shape.width
749        } else {
750            min(shape.width, context.config.chain_width())
751        }
752        .saturating_sub(almost_total);
753
754        let all_in_one_line = !self.children.iter().any(ChainItem::is_comment)
755            && self.rewrites.iter().all(|s| !s.contains('\n'))
756            && one_line_budget > 0;
757        let last_shape = if all_in_one_line {
758            shape.sub_width(last.tries, last.span)?
759        } else if extendable {
760            child_shape.sub_width(last.tries, last.span)?
761        } else {
762            child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries, last.span)?
763        };
764
765        let mut last_subexpr_str = None;
766        if all_in_one_line || extendable {
767            // First we try to 'overflow' the last child and see if it looks better than using
768            // vertical layout.
769            let one_line_shape = if context.use_block_indent() {
770                last_shape.offset_left_opt(almost_total)
771            } else {
772                last_shape
773                    .visual_indent(almost_total)
774                    .sub_width_opt(almost_total)
775            };
776
777            if let Some(one_line_shape) = one_line_shape {
778                if let Ok(rw) = last.rewrite_result(context, one_line_shape) {
779                    // We allow overflowing here only if both of the following conditions match:
780                    // 1. The entire chain fits in a single line except the last child.
781                    // 2. `last_child_str.lines().count() >= 5`.
782                    let line_count = rw.lines().count();
783                    let could_fit_single_line = first_line_width(&rw) <= one_line_budget;
784                    if could_fit_single_line && line_count >= 5 {
785                        last_subexpr_str = Some(rw);
786                        self.fits_single_line = all_in_one_line;
787                    } else {
788                        // We could not know whether overflowing is better than using vertical
789                        // layout, just by looking at the overflowed rewrite. Now we rewrite the
790                        // last child on its own line, and compare two rewrites to choose which is
791                        // better.
792                        let last_shape = child_shape.sub_width(
793                            shape.rhs_overhead(context.config) + last.tries,
794                            last.span,
795                        )?;
796                        match last.rewrite_result(context, last_shape) {
797                            Ok(ref new_rw) if !could_fit_single_line => {
798                                last_subexpr_str = Some(new_rw.clone());
799                            }
800                            Ok(ref new_rw) if new_rw.lines().count() >= line_count => {
801                                last_subexpr_str = Some(rw);
802                                self.fits_single_line = could_fit_single_line && all_in_one_line;
803                            }
804                            Ok(new_rw) => {
805                                last_subexpr_str = Some(new_rw);
806                            }
807                            _ => {
808                                last_subexpr_str = Some(rw);
809                                self.fits_single_line = could_fit_single_line && all_in_one_line;
810                            }
811                        }
812                    }
813                }
814            }
815        }
816
817        let last_shape = if context.use_block_indent() {
818            last_shape
819        } else {
820            child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries, last.span)?
821        };
822
823        let last_subexpr_str =
824            last_subexpr_str.unwrap_or(last.rewrite_result(context, last_shape)?);
825        self.rewrites.push(last_subexpr_str);
826        Ok(())
827    }
828
829    fn join_rewrites(&self, context: &RewriteContext<'_>, child_shape: Shape) -> RewriteResult {
830        let connector = if self.fits_single_line {
831            // Yay, we can put everything on one line.
832            Cow::from("")
833        } else {
834            // Use new lines.
835            if context.force_one_line_chain.get() {
836                return Err(RewriteError::ExceedsMaxWidth {
837                    configured_width: child_shape.width,
838                    span: self.children.last().unknown_error()?.span,
839                });
840            }
841            child_shape.to_string_with_newline(context.config)
842        };
843
844        let mut rewrite_iter = self.rewrites.iter();
845        let mut result = rewrite_iter.next().unwrap().clone();
846        let children_iter = self.children.iter();
847        let iter = rewrite_iter.zip(children_iter);
848
849        for (rewrite, chain_item) in iter {
850            match chain_item.kind {
851                ChainItemKind::Comment(_, CommentPosition::SameLine) => result.push(' '),
852                ChainItemKind::Comment(_, CommentPosition::DifferentLine) => {
853                    result.push_str(&connector)
854                }
855                _ => result.push_str(&connector),
856            }
857            result.push_str(rewrite);
858        }
859
860        Ok(result)
861    }
862}
863
864// Formats a chain using block indent.
865struct ChainFormatterBlock<'a> {
866    shared: ChainFormatterShared<'a>,
867    root_ends_with_block: bool,
868}
869
870impl<'a> ChainFormatterBlock<'a> {
871    fn new(chain: &'a Chain) -> ChainFormatterBlock<'a> {
872        ChainFormatterBlock {
873            shared: ChainFormatterShared::new(chain),
874            root_ends_with_block: false,
875        }
876    }
877}
878
879impl<'a> ChainFormatter for ChainFormatterBlock<'a> {
880    fn format_root(
881        &mut self,
882        parent: &ChainItem,
883        context: &RewriteContext<'_>,
884        shape: Shape,
885    ) -> Result<(), RewriteError> {
886        let mut root_rewrite: String = parent.rewrite_result(context, shape)?;
887
888        let mut root_ends_with_block = parent.kind.is_block_like(context, &root_rewrite);
889        let tab_width = context.config.tab_spaces().saturating_sub(shape.offset);
890
891        while root_rewrite.len() <= tab_width && !root_rewrite.contains('\n') {
892            let item = &self.shared.children[0];
893            if let ChainItemKind::Comment(..) = item.kind {
894                break;
895            }
896            let shape = shape.offset_left(root_rewrite.len(), item.span)?;
897            match &item.rewrite_result(context, shape) {
898                Ok(rewrite) => root_rewrite.push_str(rewrite),
899                Err(_) => break,
900            }
901
902            root_ends_with_block = last_line_extendable(&root_rewrite);
903
904            self.shared.children = &self.shared.children[1..];
905            if self.shared.children.is_empty() {
906                break;
907            }
908        }
909        self.shared.rewrites.push(root_rewrite);
910        self.root_ends_with_block = root_ends_with_block;
911        Ok(())
912    }
913
914    fn child_shape(
915        &self,
916        context: &RewriteContext<'_>,
917        shape: Shape,
918        _span: Span,
919    ) -> Result<Shape, ExceedsMaxWidthError> {
920        let block_end = self.root_ends_with_block;
921        Ok(get_block_child_shape(block_end, context, shape))
922    }
923
924    fn format_children(
925        &mut self,
926        context: &RewriteContext<'_>,
927        child_shape: Shape,
928    ) -> Result<(), RewriteError> {
929        self.shared.format_children(context, child_shape)
930    }
931
932    fn format_last_child(
933        &mut self,
934        context: &RewriteContext<'_>,
935        shape: Shape,
936        child_shape: Shape,
937    ) -> Result<(), RewriteError> {
938        self.shared
939            .format_last_child(true, context, shape, child_shape)
940    }
941
942    fn join_rewrites(&self, context: &RewriteContext<'_>, child_shape: Shape) -> RewriteResult {
943        self.shared.join_rewrites(context, child_shape)
944    }
945
946    fn pure_root(&mut self) -> Option<String> {
947        self.shared.pure_root()
948    }
949}
950
951// Format a chain using visual indent.
952struct ChainFormatterVisual<'a> {
953    shared: ChainFormatterShared<'a>,
954    // The extra offset from the chain's shape to the position of the `.`
955    offset: usize,
956}
957
958impl<'a> ChainFormatterVisual<'a> {
959    fn new(chain: &'a Chain) -> ChainFormatterVisual<'a> {
960        ChainFormatterVisual {
961            shared: ChainFormatterShared::new(chain),
962            offset: 0,
963        }
964    }
965}
966
967impl<'a> ChainFormatter for ChainFormatterVisual<'a> {
968    fn format_root(
969        &mut self,
970        parent: &ChainItem,
971        context: &RewriteContext<'_>,
972        shape: Shape,
973    ) -> Result<(), RewriteError> {
974        let parent_shape = shape.visual_indent(0);
975        let mut root_rewrite = parent.rewrite_result(context, parent_shape)?;
976        let multiline = root_rewrite.contains('\n');
977        self.offset = if multiline {
978            last_line_width(&root_rewrite, context.config.tab_spaces())
979                .saturating_sub(shape.used_width())
980        } else {
981            trimmed_last_line_width(&root_rewrite)
982        };
983
984        if !multiline || parent.kind.is_block_like(context, &root_rewrite) {
985            let item = &self.shared.children[0];
986            if let ChainItemKind::Comment(..) = item.kind {
987                self.shared.rewrites.push(root_rewrite);
988                return Ok(());
989            }
990            let child_shape = parent_shape
991                .visual_indent(self.offset)
992                .sub_width(self.offset, item.span)?;
993            let rewrite = item.rewrite_result(context, child_shape)?;
994            if filtered_str_fits(
995                &rewrite,
996                context.config.max_width(),
997                context.config.tab_spaces(),
998                shape,
999            ) {
1000                root_rewrite.push_str(&rewrite);
1001            } else {
1002                // We couldn't fit in at the visual indent, try the last
1003                // indent.
1004                let rewrite = item.rewrite_result(context, parent_shape)?;
1005                root_rewrite.push_str(&rewrite);
1006                self.offset = 0;
1007            }
1008
1009            self.shared.children = &self.shared.children[1..];
1010        }
1011
1012        self.shared.rewrites.push(root_rewrite);
1013        Ok(())
1014    }
1015
1016    fn child_shape(
1017        &self,
1018        context: &RewriteContext<'_>,
1019        shape: Shape,
1020        span: Span,
1021    ) -> Result<Shape, ExceedsMaxWidthError> {
1022        get_visual_style_child_shape(
1023            context,
1024            shape,
1025            self.offset,
1026            // TODO(calebcartwright): self.shared.permissibly_overflowing_parent,
1027            false,
1028            span,
1029        )
1030    }
1031
1032    fn format_children(
1033        &mut self,
1034        context: &RewriteContext<'_>,
1035        child_shape: Shape,
1036    ) -> Result<(), RewriteError> {
1037        self.shared.format_children(context, child_shape)
1038    }
1039
1040    fn format_last_child(
1041        &mut self,
1042        context: &RewriteContext<'_>,
1043        shape: Shape,
1044        child_shape: Shape,
1045    ) -> Result<(), RewriteError> {
1046        self.shared
1047            .format_last_child(false, context, shape, child_shape)
1048    }
1049
1050    fn join_rewrites(&self, context: &RewriteContext<'_>, child_shape: Shape) -> RewriteResult {
1051        self.shared.join_rewrites(context, child_shape)
1052    }
1053
1054    fn pure_root(&mut self) -> Option<String> {
1055        self.shared.pure_root()
1056    }
1057}
1058
1059/// Removes try operators (`?`s) that appear in the given string. If removing
1060/// them leaves an empty line, remove that line as well unless it is the first
1061/// line (we need the first newline for detecting pre/post comment).
1062fn trim_tries(s: &str) -> String {
1063    let mut result = String::with_capacity(s.len());
1064    let mut line_buffer = String::with_capacity(s.len());
1065    for (kind, rich_char) in CharClasses::new(s.chars()) {
1066        match rich_char.get_char() {
1067            '\n' => {
1068                if result.is_empty() || !line_buffer.trim().is_empty() {
1069                    result.push_str(&line_buffer);
1070                    result.push('\n')
1071                }
1072                line_buffer.clear();
1073            }
1074            '?' if kind == FullCodeCharKind::Normal => continue,
1075            c => line_buffer.push(c),
1076        }
1077    }
1078    if !line_buffer.trim().is_empty() {
1079        result.push_str(&line_buffer);
1080    }
1081    result
1082}
1083
1084/// Whether a method call's receiver needs parenthesis, like
1085/// ```rust,ignore
1086/// || .. .method();
1087/// || 1.. .method();
1088/// 1. .method();
1089/// ```
1090/// Which all need parenthesis or a space before `.method()`.
1091fn should_add_parens(expr: &ast::Expr, context: &RewriteContext<'_>) -> bool {
1092    match expr.kind {
1093        ast::ExprKind::Lit(ref lit) => crate::expr::lit_ends_in_dot(lit, context),
1094        ast::ExprKind::Closure(ref cl) => match cl.body.kind {
1095            ast::ExprKind::Range(_, _, ast::RangeLimits::HalfOpen) => true,
1096            ast::ExprKind::Lit(ref lit) => crate::expr::lit_ends_in_dot(lit, context),
1097            _ => false,
1098        },
1099        _ => false,
1100    }
1101}