1 //! Formatting of chained expressions, i.e., expressions that are chained by
2 //! dots: struct and enum field access, method calls, and try shorthand (`?`).
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.
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.
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
15 //! E.g., `let foo = { aaaa; bbb; ccc }.bar.baz();`, we would layout for the
16 //! following values of `chain_indent`:
40 //! If the first item in the chain is a block expression, we align the dots with
61 use syntax::source_map::{BytePos, Span};
62 use syntax::{ast, ptr};
64 use crate::comment::{rewrite_comment, CharClasses, FullCodeCharKind, RichChar};
65 use crate::config::IndentStyle;
66 use crate::expr::rewrite_call;
67 use crate::lists::extract_pre_comment;
68 use crate::macros::convert_try_mac;
69 use crate::rewrite::{Rewrite, RewriteContext};
70 use crate::shape::Shape;
71 use crate::source_map::SpanUtils;
73 self, first_line_width, last_line_extendable, last_line_width, mk_sp, rewrite_ident,
74 trimmed_last_line_width, wrap_str,
79 context: &RewriteContext<'_>,
82 let chain = Chain::from_ast(expr, context);
83 debug!("rewrite_chain {:?} {:?}", chain, shape);
85 // If this is just an expression with some `?`s, then format it trivially and
87 if chain.children.is_empty() {
88 return chain.parent.rewrite(context, shape);
91 chain.rewrite(context, shape)
95 enum CommentPosition {
100 // An expression plus trailing `?`s to be formatted together.
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.
116 Vec<ast::GenericArg>,
117 Vec<ptr::P<ast::Expr>>,
119 StructField(ast::Ident),
120 TupleField(ast::Ident, bool),
121 Comment(String, CommentPosition),
125 fn is_block_like(&self, context: &RewriteContext<'_>, reps: &str) -> bool {
127 ChainItemKind::Parent(ref expr) => utils::is_block_expr(context, expr, reps),
128 ChainItemKind::MethodCall(..)
129 | ChainItemKind::StructField(..)
130 | ChainItemKind::TupleField(..)
131 | ChainItemKind::Comment(..) => false,
135 fn is_tup_field_access(expr: &ast::Expr) -> bool {
137 ast::ExprKind::Field(_, ref field) => {
138 field.name.to_string().chars().all(|c| c.is_digit(10))
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 {
156 let span = mk_sp(expressions[0].span.hi(), expr.span.hi());
157 let kind = ChainItemKind::MethodCall(segment.clone(), types, expressions.clone());
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))
164 ChainItemKind::StructField(field)
166 let span = mk_sp(nested.span.hi(), field.span.hi());
169 _ => return (ChainItemKind::Parent(expr.clone()), expr.span),
172 // Remove comments from the span.
173 let lo = context.snippet_provider.span_before(span, ".");
174 (kind, mk_sp(lo, span.hi()))
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)?
186 ChainItemKind::StructField(ident) => format!(".{}", rewrite_ident(context, ident)),
187 ChainItemKind::TupleField(ident, nested) => format!(
189 if nested { " " } else { "" },
190 rewrite_ident(context, ident)
192 ChainItemKind::Comment(ref comment, _) => {
193 rewrite_comment(comment, false, shape, context.config)?
196 Some(format!("{}{}", rewrite, "?".repeat(self.tries)))
201 fn new(context: &RewriteContext<'_>, expr: &ast::Expr, tries: usize) -> ChainItem {
202 let (kind, span) = ChainItemKind::from_ast(context, expr);
203 ChainItem { kind, tries, span }
206 fn comment(span: Span, comment: String, pos: CommentPosition) -> ChainItem {
208 kind: ChainItemKind::Comment(comment, pos),
214 fn is_comment(&self) -> bool {
216 ChainItemKind::Comment(..) => true,
221 fn rewrite_method_call(
222 method_name: ast::Ident,
223 types: &[ast::GenericArg],
224 args: &[ptr::P<ast::Expr>],
226 context: &RewriteContext<'_>,
228 ) -> Option<String> {
229 let type_str = if types.is_empty() {
232 let type_list = types
234 .map(|ty| ty.rewrite(context, shape))
235 .collect::<Option<Vec<_>>>()?;
237 format!("::<{}>", type_list.join(", "))
239 let callee_str = format!(".{}{}", rewrite_ident(context, method_name), type_str);
240 rewrite_call(context, &callee_str, &args[1..], span, shape)
247 children: Vec<ChainItem>,
251 fn from_ast(expr: &ast::Expr, context: &RewriteContext<'_>) -> Chain {
252 let subexpr_list = Self::make_subexpr_list(expr, context);
254 // Un-parse the expression tree into ChainItems
255 let mut rev_children = vec![];
256 let mut sub_tries = 0;
257 for subexpr in &subexpr_list {
259 ast::ExprKind::Try(_) => sub_tries += 1,
261 rev_children.push(ChainItem::new(context, subexpr, sub_tries));
267 fn is_tries(s: &str) -> bool {
268 s.chars().all(|c| c == '?')
271 fn is_post_comment(s: &str) -> bool {
272 let comment_start_index = s.chars().position(|c| c == '/');
273 if comment_start_index.is_none() {
277 let newline_index = s.chars().position(|c| c == '\n');
278 if newline_index.is_none() {
282 comment_start_index.unwrap() < newline_index.unwrap()
285 fn handle_post_comment(
286 post_comment_span: Span,
287 post_comment_snippet: &str,
288 prev_span_end: &mut BytePos,
289 children: &mut Vec<ChainItem>,
291 let white_spaces: &[_] = &[' ', '\t'];
292 if post_comment_snippet
293 .trim_matches(white_spaces)
299 let trimmed_snippet = trim_tries(post_comment_snippet);
300 if is_post_comment(&trimmed_snippet) {
301 children.push(ChainItem::comment(
303 trimmed_snippet.trim().to_owned(),
304 CommentPosition::Back,
306 *prev_span_end = post_comment_span.hi();
310 let parent = rev_children.pop().unwrap();
311 let mut children = vec![];
312 let mut prev_span_end = parent.span.hi();
313 let mut iter = rev_children.into_iter().rev().peekable();
314 if let Some(first_chain_item) = iter.peek() {
315 let comment_span = mk_sp(prev_span_end, first_chain_item.span.lo());
316 let comment_snippet = context.snippet(comment_span);
317 if !is_tries(comment_snippet.trim()) {
326 while let Some(chain_item) = iter.next() {
327 let comment_snippet = context.snippet(chain_item.span);
328 // FIXME: Figure out the way to get a correct span when converting `try!` to `?`.
330 !(context.config.use_try_shorthand() || is_tries(comment_snippet.trim()));
334 let pre_comment_span = mk_sp(prev_span_end, chain_item.span.lo());
335 let pre_comment_snippet = trim_tries(context.snippet(pre_comment_span));
336 let (pre_comment, _) = extract_pre_comment(&pre_comment_snippet);
338 Some(ref comment) if !comment.is_empty() => {
339 children.push(ChainItem::comment(
342 CommentPosition::Top,
349 prev_span_end = chain_item.span.hi();
350 children.push(chain_item);
353 if !handle_comment || iter.peek().is_none() {
357 let next_lo = iter.peek().unwrap().span.lo();
358 let post_comment_span = mk_sp(prev_span_end, next_lo);
359 let post_comment_snippet = context.snippet(post_comment_span);
362 post_comment_snippet,
368 Chain { parent, children }
371 // Returns a Vec of the prefixes of the chain.
372 // E.g., for input `a.b.c` we return [`a.b.c`, `a.b`, 'a']
373 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext<'_>) -> Vec<ast::Expr> {
374 let mut subexpr_list = vec![expr.clone()];
376 while let Some(subexpr) = Self::pop_expr_chain(subexpr_list.last().unwrap(), context) {
377 subexpr_list.push(subexpr.clone());
383 // Returns the expression's subexpression, if it exists. When the subexpr
384 // is a try! macro, we'll convert it to shorthand when the option is set.
385 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext<'_>) -> Option<ast::Expr> {
387 ast::ExprKind::MethodCall(_, ref expressions) => {
388 Some(Self::convert_try(&expressions[0], context))
390 ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) => {
391 Some(Self::convert_try(subexpr, context))
397 fn convert_try(expr: &ast::Expr, context: &RewriteContext<'_>) -> ast::Expr {
399 ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
400 if let Some(subexpr) = convert_try_mac(mac, context) {
411 impl Rewrite for Chain {
412 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
413 debug!("rewrite chain {:?} {:?}", self, shape);
415 let mut formatter = match context.config.indent_style() {
416 IndentStyle::Block => {
417 Box::new(ChainFormatterBlock::new(self)) as Box<dyn ChainFormatter>
419 IndentStyle::Visual => {
420 Box::new(ChainFormatterVisual::new(self)) as Box<dyn ChainFormatter>
424 formatter.format_root(&self.parent, context, shape)?;
425 if let Some(result) = formatter.pure_root() {
426 return wrap_str(result, context.config.max_width(), shape);
429 // Decide how to layout the rest of the chain.
430 let child_shape = formatter.child_shape(context, shape)?;
432 formatter.format_children(context, child_shape)?;
433 formatter.format_last_child(context, shape, child_shape)?;
435 let result = formatter.join_rewrites(context, child_shape)?;
436 wrap_str(result, context.config.max_width(), shape)
440 // There are a few types for formatting chains. This is because there is a lot
441 // in common between formatting with block vs visual indent, but they are
442 // different enough that branching on the indent all over the place gets ugly.
443 // Anything that can format a chain is a ChainFormatter.
444 trait ChainFormatter {
445 // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
446 // Root is the parent plus any other chain items placed on the first line to
447 // avoid an orphan. E.g.,
452 // If `bar` were not part of the root, then foo would be orphaned and 'float'.
456 context: &RewriteContext<'_>,
459 fn child_shape(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<Shape>;
460 fn format_children(&mut self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<()>;
461 fn format_last_child(
463 context: &RewriteContext<'_>,
467 fn join_rewrites(&self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<String>;
468 // Returns `Some` if the chain is only a root, None otherwise.
469 fn pure_root(&mut self) -> Option<String>;
472 // Data and behaviour that is shared by both chain formatters. The concrete
473 // formatters can delegate much behaviour to `ChainFormatterShared`.
474 struct ChainFormatterShared<'a> {
475 // The current working set of child items.
476 children: &'a [ChainItem],
477 // The current rewrites of items (includes trailing `?`s, but not any way to
478 // connect the rewrites together).
479 rewrites: Vec<String>,
480 // Whether the chain can fit on one line.
481 fits_single_line: bool,
482 // The number of children in the chain. This is not equal to `self.children.len()`
483 // because `self.children` will change size as we process the chain.
487 impl<'a> ChainFormatterShared<'a> {
488 fn new(chain: &'a Chain) -> ChainFormatterShared<'a> {
489 ChainFormatterShared {
490 children: &chain.children,
491 rewrites: Vec::with_capacity(chain.children.len() + 1),
492 fits_single_line: false,
493 child_count: chain.children.len(),
497 fn pure_root(&mut self) -> Option<String> {
498 if self.children.is_empty() {
499 assert_eq!(self.rewrites.len(), 1);
500 Some(self.rewrites.pop().unwrap())
506 // Rewrite the last child. The last child of a chain requires special treatment. We need to
507 // know whether 'overflowing' the last child make a better formatting:
509 // A chain with overflowing the last child:
511 // parent.child1.child2.last_child(
518 // A chain without overflowing the last child (in vertical layout):
523 // .last_child(a, b, c)
526 // In particular, overflowing is effective when the last child is a method with a multi-lined
527 // block-like argument (e.g., closure):
529 // parent.child1.child2.last_child(|a, b, c| {
530 // let x = foo(a, b, c);
531 // let y = bar(a, b, c);
538 fn format_last_child(
541 context: &RewriteContext<'_>,
545 let last = self.children.last()?;
546 let extendable = may_extend && last_line_extendable(&self.rewrites[0]);
547 let prev_last_line_width = last_line_width(&self.rewrites[0]);
549 // Total of all items excluding the last.
550 let almost_total = if extendable {
553 self.rewrites.iter().map(String::len).sum()
555 let one_line_budget = if self.child_count == 1 {
558 min(shape.width, context.config.width_heuristics().chain_width)
560 .saturating_sub(almost_total);
562 let all_in_one_line = !self.children.iter().any(ChainItem::is_comment)
563 && self.rewrites.iter().all(|s| !s.contains('\n'))
564 && one_line_budget > 0;
565 let last_shape = if all_in_one_line {
566 shape.sub_width(last.tries)?
567 } else if extendable {
568 child_shape.sub_width(last.tries)?
570 child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?
573 let mut last_subexpr_str = None;
574 if all_in_one_line || extendable {
575 // First we try to 'overflow' the last child and see if it looks better than using
577 let one_line_shape = if context.use_block_indent() {
578 last_shape.offset_left(almost_total)
581 .visual_indent(almost_total)
582 .sub_width(almost_total)
585 if let Some(one_line_shape) = one_line_shape {
586 if let Some(rw) = last.rewrite(context, one_line_shape) {
587 // We allow overflowing here only if both of the following conditions match:
588 // 1. The entire chain fits in a single line except the last child.
589 // 2. `last_child_str.lines().count() >= 5`.
590 let line_count = rw.lines().count();
591 let could_fit_single_line = first_line_width(&rw) <= one_line_budget;
592 if could_fit_single_line && line_count >= 5 {
593 last_subexpr_str = Some(rw);
594 self.fits_single_line = all_in_one_line;
596 // We could not know whether overflowing is better than using vertical
597 // layout, just by looking at the overflowed rewrite. Now we rewrite the
598 // last child on its own line, and compare two rewrites to choose which is
600 let last_shape = child_shape
601 .sub_width(shape.rhs_overhead(context.config) + last.tries)?;
602 match last.rewrite(context, last_shape) {
603 Some(ref new_rw) if !could_fit_single_line => {
604 last_subexpr_str = Some(new_rw.clone());
606 Some(ref new_rw) if new_rw.lines().count() >= line_count => {
607 last_subexpr_str = Some(rw);
608 self.fits_single_line = could_fit_single_line && all_in_one_line;
610 new_rw @ Some(..) => {
611 last_subexpr_str = new_rw;
614 last_subexpr_str = Some(rw);
615 self.fits_single_line = could_fit_single_line && all_in_one_line;
623 let last_shape = if context.use_block_indent() {
626 child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?
629 last_subexpr_str = last_subexpr_str.or_else(|| last.rewrite(context, last_shape));
630 self.rewrites.push(last_subexpr_str?);
634 fn join_rewrites(&self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<String> {
635 let connector = if self.fits_single_line {
636 // Yay, we can put everything on one line.
640 if *context.force_one_line_chain.borrow() {
643 child_shape.to_string_with_newline(context.config)
646 let mut rewrite_iter = self.rewrites.iter();
647 let mut result = rewrite_iter.next().unwrap().clone();
648 let children_iter = self.children.iter();
649 let iter = rewrite_iter.zip(children_iter);
651 for (rewrite, chain_item) in iter {
652 match chain_item.kind {
653 ChainItemKind::Comment(_, CommentPosition::Back) => result.push(' '),
654 ChainItemKind::Comment(_, CommentPosition::Top) => result.push_str(&connector),
655 _ => result.push_str(&connector),
657 result.push_str(&rewrite);
664 // Formats a chain using block indent.
665 struct ChainFormatterBlock<'a> {
666 shared: ChainFormatterShared<'a>,
667 root_ends_with_block: bool,
670 impl<'a> ChainFormatterBlock<'a> {
671 fn new(chain: &'a Chain) -> ChainFormatterBlock<'a> {
672 ChainFormatterBlock {
673 shared: ChainFormatterShared::new(chain),
674 root_ends_with_block: false,
679 impl<'a> ChainFormatter for ChainFormatterBlock<'a> {
683 context: &RewriteContext<'_>,
686 let mut root_rewrite: String = parent.rewrite(context, shape)?;
688 let mut root_ends_with_block = parent.kind.is_block_like(context, &root_rewrite);
689 let tab_width = context.config.tab_spaces().saturating_sub(shape.offset);
691 while root_rewrite.len() <= tab_width && !root_rewrite.contains('\n') {
692 let item = &self.shared.children[0];
693 if let ChainItemKind::Comment(..) = item.kind {
696 let shape = shape.offset_left(root_rewrite.len())?;
697 match &item.rewrite(context, shape) {
698 Some(rewrite) => root_rewrite.push_str(rewrite),
702 root_ends_with_block = last_line_extendable(&root_rewrite);
704 self.shared.children = &self.shared.children[1..];
705 if self.shared.children.is_empty() {
709 self.shared.rewrites.push(root_rewrite);
710 self.root_ends_with_block = root_ends_with_block;
714 fn child_shape(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<Shape> {
716 if self.root_ends_with_block {
717 shape.block_indent(0)
719 shape.block_indent(context.config.tab_spaces())
721 .with_max_width(context.config),
725 fn format_children(&mut self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<()> {
726 for item in &self.shared.children[..self.shared.children.len() - 1] {
727 let rewrite = item.rewrite(context, child_shape)?;
728 self.shared.rewrites.push(rewrite);
733 fn format_last_child(
735 context: &RewriteContext<'_>,
740 .format_last_child(true, context, shape, child_shape)
743 fn join_rewrites(&self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<String> {
744 self.shared.join_rewrites(context, child_shape)
747 fn pure_root(&mut self) -> Option<String> {
748 self.shared.pure_root()
752 // Format a chain using visual indent.
753 struct ChainFormatterVisual<'a> {
754 shared: ChainFormatterShared<'a>,
755 // The extra offset from the chain's shape to the position of the `.`
759 impl<'a> ChainFormatterVisual<'a> {
760 fn new(chain: &'a Chain) -> ChainFormatterVisual<'a> {
761 ChainFormatterVisual {
762 shared: ChainFormatterShared::new(chain),
768 impl<'a> ChainFormatter for ChainFormatterVisual<'a> {
772 context: &RewriteContext<'_>,
775 let parent_shape = shape.visual_indent(0);
776 let mut root_rewrite = parent.rewrite(context, parent_shape)?;
777 let multiline = root_rewrite.contains('\n');
778 self.offset = if multiline {
779 last_line_width(&root_rewrite).saturating_sub(shape.used_width())
781 trimmed_last_line_width(&root_rewrite)
784 if !multiline || parent.kind.is_block_like(context, &root_rewrite) {
785 let item = &self.shared.children[0];
786 if let ChainItemKind::Comment(..) = item.kind {
787 self.shared.rewrites.push(root_rewrite);
790 let child_shape = parent_shape
791 .visual_indent(self.offset)
792 .sub_width(self.offset)?;
793 let rewrite = item.rewrite(context, child_shape)?;
794 match wrap_str(rewrite, context.config.max_width(), shape) {
795 Some(rewrite) => root_rewrite.push_str(&rewrite),
797 // We couldn't fit in at the visual indent, try the last
799 let rewrite = item.rewrite(context, parent_shape)?;
800 root_rewrite.push_str(&rewrite);
805 self.shared.children = &self.shared.children[1..];
808 self.shared.rewrites.push(root_rewrite);
812 fn child_shape(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<Shape> {
814 .with_max_width(context.config)
815 .offset_left(self.offset)
816 .map(|s| s.visual_indent(0))
819 fn format_children(&mut self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<()> {
820 for item in &self.shared.children[..self.shared.children.len() - 1] {
821 let rewrite = item.rewrite(context, child_shape)?;
822 self.shared.rewrites.push(rewrite);
827 fn format_last_child(
829 context: &RewriteContext<'_>,
834 .format_last_child(false, context, shape, child_shape)
837 fn join_rewrites(&self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<String> {
838 self.shared.join_rewrites(context, child_shape)
841 fn pure_root(&mut self) -> Option<String> {
842 self.shared.pure_root()
846 /// Removes try operators (`?`s) that appear in the given string. If removing
847 /// them leaves an empty line, remove that line as well unless it is the first
848 /// line (we need the first newline for detecting pre/post comment).
849 fn trim_tries(s: &str) -> String {
850 let mut result = String::with_capacity(s.len());
851 let mut line_buffer = String::with_capacity(s.len());
852 for (kind, rich_char) in CharClasses::new(s.chars()) {
853 match rich_char.get_char() {
855 if result.is_empty() || !line_buffer.trim().is_empty() {
856 result.push_str(&line_buffer);
861 '?' if kind == FullCodeCharKind::Normal => continue,
862 c => line_buffer.push(c),
865 if !line_buffer.trim().is_empty() {
866 result.push_str(&line_buffer);