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.
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.
11 //! Formatting of chained expressions, i.e. expressions which are chained by
12 //! dots: struct and enum field access, method calls, and try shorthand (?).
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.
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.
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
25 //! E.g., `let foo = { aaaa; bbb; ccc }.bar.baz();`, we would layout for the
26 //! following values of `chain_indent`:
50 //! If the first item in the chain is a block expression, we align the dots with
71 use syntax::source_map::{BytePos, Span};
72 use syntax::{ast, ptr};
74 use crate::comment::{rewrite_comment, CharClasses, FullCodeCharKind, RichChar};
75 use crate::config::IndentStyle;
76 use crate::expr::rewrite_call;
77 use crate::lists::extract_pre_comment;
78 use crate::macros::convert_try_mac;
79 use crate::rewrite::{Rewrite, RewriteContext};
80 use crate::shape::Shape;
81 use crate::source_map::SpanUtils;
83 self, first_line_width, last_line_extendable, last_line_width, mk_sp, rewrite_ident,
84 trimmed_last_line_width, wrap_str,
89 context: &RewriteContext<'_>,
92 let chain = Chain::from_ast(expr, context);
93 debug!("rewrite_chain {:?} {:?}", chain, shape);
95 // If this is just an expression with some `?`s, then format it trivially and
97 if chain.children.is_empty() {
98 return chain.parent.rewrite(context, shape);
101 chain.rewrite(context, shape)
105 enum CommentPosition {
110 // An expression plus trailing `?`s to be formatted together.
118 // FIXME: we can't use a reference here because to convert `try!` to `?` we
119 // synthesise the AST node. However, I think we could use `Cow` and that
120 // would remove a lot of cloning.
126 Vec<ast::GenericArg>,
127 Vec<ptr::P<ast::Expr>>,
129 StructField(ast::Ident),
130 TupleField(ast::Ident, bool),
131 Comment(String, CommentPosition),
135 fn is_block_like(&self, context: &RewriteContext<'_>, reps: &str) -> bool {
137 ChainItemKind::Parent(ref expr) => utils::is_block_expr(context, expr, reps),
138 ChainItemKind::MethodCall(..)
139 | ChainItemKind::StructField(..)
140 | ChainItemKind::TupleField(..)
141 | ChainItemKind::Comment(..) => false,
145 fn is_tup_field_access(expr: &ast::Expr) -> bool {
147 ast::ExprKind::Field(_, ref field) => {
148 field.name.to_string().chars().all(|c| c.is_digit(10))
154 fn from_ast(context: &RewriteContext<'_>, expr: &ast::Expr) -> (ChainItemKind, Span) {
155 let (kind, span) = match expr.node {
156 ast::ExprKind::MethodCall(ref segment, ref expressions) => {
157 let types = if let Some(ref generic_args) = segment.args {
158 if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
166 let span = mk_sp(expressions[0].span.hi(), expr.span.hi());
167 let kind = ChainItemKind::MethodCall(segment.clone(), types, expressions.clone());
170 ast::ExprKind::Field(ref nested, field) => {
171 let kind = if Self::is_tup_field_access(expr) {
172 ChainItemKind::TupleField(field, Self::is_tup_field_access(nested))
174 ChainItemKind::StructField(field)
176 let span = mk_sp(nested.span.hi(), field.span.hi());
179 _ => return (ChainItemKind::Parent(expr.clone()), expr.span),
182 // Remove comments from the span.
183 let lo = context.snippet_provider.span_before(span, ".");
184 (kind, mk_sp(lo, span.hi()))
188 impl Rewrite for ChainItem {
189 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
190 let shape = shape.sub_width(self.tries)?;
191 let rewrite = match self.kind {
192 ChainItemKind::Parent(ref expr) => expr.rewrite(context, shape)?,
193 ChainItemKind::MethodCall(ref segment, ref types, ref exprs) => {
194 Self::rewrite_method_call(segment.ident, types, exprs, self.span, context, shape)?
196 ChainItemKind::StructField(ident) => format!(".{}", rewrite_ident(context, ident)),
197 ChainItemKind::TupleField(ident, nested) => format!(
199 if nested { " " } else { "" },
200 rewrite_ident(context, ident)
202 ChainItemKind::Comment(ref comment, _) => {
203 rewrite_comment(comment, false, shape, context.config)?
206 Some(format!("{}{}", rewrite, "?".repeat(self.tries)))
211 fn new(context: &RewriteContext<'_>, expr: &ast::Expr, tries: usize) -> ChainItem {
212 let (kind, span) = ChainItemKind::from_ast(context, expr);
213 ChainItem { kind, tries, span }
216 fn comment(span: Span, comment: String, pos: CommentPosition) -> ChainItem {
218 kind: ChainItemKind::Comment(comment, pos),
224 fn is_comment(&self) -> bool {
226 ChainItemKind::Comment(..) => true,
231 fn rewrite_method_call(
232 method_name: ast::Ident,
233 types: &[ast::GenericArg],
234 args: &[ptr::P<ast::Expr>],
236 context: &RewriteContext<'_>,
238 ) -> Option<String> {
239 let type_str = if types.is_empty() {
242 let type_list = types
244 .map(|ty| ty.rewrite(context, shape))
245 .collect::<Option<Vec<_>>>()?;
247 format!("::<{}>", type_list.join(", "))
249 let callee_str = format!(".{}{}", rewrite_ident(context, method_name), type_str);
250 rewrite_call(context, &callee_str, &args[1..], span, shape)
257 children: Vec<ChainItem>,
261 fn from_ast(expr: &ast::Expr, context: &RewriteContext<'_>) -> Chain {
262 let subexpr_list = Self::make_subexpr_list(expr, context);
264 // Un-parse the expression tree into ChainItems
265 let mut rev_children = vec![];
266 let mut sub_tries = 0;
267 for subexpr in &subexpr_list {
269 ast::ExprKind::Try(_) => sub_tries += 1,
271 rev_children.push(ChainItem::new(context, subexpr, sub_tries));
277 fn is_tries(s: &str) -> bool {
278 s.chars().all(|c| c == '?')
281 fn is_post_comment(s: &str) -> bool {
282 let comment_start_index = s.chars().position(|c| c == '/');
283 if comment_start_index.is_none() {
287 let newline_index = s.chars().position(|c| c == '\n');
288 if newline_index.is_none() {
292 comment_start_index.unwrap() < newline_index.unwrap()
295 fn handle_post_comment(
296 post_comment_span: Span,
297 post_comment_snippet: &str,
298 prev_span_end: &mut BytePos,
299 children: &mut Vec<ChainItem>,
301 let white_spaces: &[_] = &[' ', '\t'];
302 if post_comment_snippet
303 .trim_matches(white_spaces)
309 let trimmed_snippet = trim_tries(post_comment_snippet);
310 if is_post_comment(&trimmed_snippet) {
311 children.push(ChainItem::comment(
313 trimmed_snippet.trim().to_owned(),
314 CommentPosition::Back,
316 *prev_span_end = post_comment_span.hi();
320 let parent = rev_children.pop().unwrap();
321 let mut children = vec![];
322 let mut prev_span_end = parent.span.hi();
323 let mut iter = rev_children.into_iter().rev().peekable();
324 if let Some(first_chain_item) = iter.peek() {
325 let comment_span = mk_sp(prev_span_end, first_chain_item.span.lo());
326 let comment_snippet = context.snippet(comment_span);
327 if !is_tries(comment_snippet.trim()) {
336 while let Some(chain_item) = iter.next() {
337 let comment_snippet = context.snippet(chain_item.span);
338 // FIXME: Figure out the way to get a correct span when converting `try!` to `?`.
340 !(context.config.use_try_shorthand() || is_tries(comment_snippet.trim()));
344 let pre_comment_span = mk_sp(prev_span_end, chain_item.span.lo());
345 let pre_comment_snippet = trim_tries(context.snippet(pre_comment_span));
346 let (pre_comment, _) = extract_pre_comment(&pre_comment_snippet);
348 Some(ref comment) if !comment.is_empty() => {
349 children.push(ChainItem::comment(
352 CommentPosition::Top,
359 prev_span_end = chain_item.span.hi();
360 children.push(chain_item);
363 if !handle_comment || iter.peek().is_none() {
367 let next_lo = iter.peek().unwrap().span.lo();
368 let post_comment_span = mk_sp(prev_span_end, next_lo);
369 let post_comment_snippet = context.snippet(post_comment_span);
372 post_comment_snippet,
378 Chain { parent, children }
381 // Returns a Vec of the prefixes of the chain.
382 // E.g., for input `a.b.c` we return [`a.b.c`, `a.b`, 'a']
383 fn make_subexpr_list(expr: &ast::Expr, context: &RewriteContext<'_>) -> Vec<ast::Expr> {
384 let mut subexpr_list = vec![expr.clone()];
386 while let Some(subexpr) = Self::pop_expr_chain(subexpr_list.last().unwrap(), context) {
387 subexpr_list.push(subexpr.clone());
393 // Returns the expression's subexpression, if it exists. When the subexpr
394 // is a try! macro, we'll convert it to shorthand when the option is set.
395 fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext<'_>) -> Option<ast::Expr> {
397 ast::ExprKind::MethodCall(_, ref expressions) => {
398 Some(Self::convert_try(&expressions[0], context))
400 ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) => {
401 Some(Self::convert_try(subexpr, context))
407 fn convert_try(expr: &ast::Expr, context: &RewriteContext<'_>) -> ast::Expr {
409 ast::ExprKind::Mac(ref mac) if context.config.use_try_shorthand() => {
410 if let Some(subexpr) = convert_try_mac(mac, context) {
421 impl Rewrite for Chain {
422 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
423 debug!("rewrite chain {:?} {:?}", self, shape);
425 let mut formatter = match context.config.indent_style() {
426 IndentStyle::Block => {
427 Box::new(ChainFormatterBlock::new(self)) as Box<dyn ChainFormatter>
429 IndentStyle::Visual => {
430 Box::new(ChainFormatterVisual::new(self)) as Box<dyn ChainFormatter>
434 formatter.format_root(&self.parent, context, shape)?;
435 if let Some(result) = formatter.pure_root() {
436 return wrap_str(result, context.config.max_width(), shape);
439 // Decide how to layout the rest of the chain.
440 let child_shape = formatter.child_shape(context, shape)?;
442 formatter.format_children(context, child_shape)?;
443 formatter.format_last_child(context, shape, child_shape)?;
445 let result = formatter.join_rewrites(context, child_shape)?;
446 wrap_str(result, context.config.max_width(), shape)
450 // There are a few types for formatting chains. This is because there is a lot
451 // in common between formatting with block vs visual indent, but they are
452 // different enough that branching on the indent all over the place gets ugly.
453 // Anything that can format a chain is a ChainFormatter.
454 trait ChainFormatter {
455 // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
456 // Root is the parent plus any other chain items placed on the first line to
457 // avoid an orphan. E.g.,
462 // If `bar` were not part of the root, then foo would be orphaned and 'float'.
466 context: &RewriteContext<'_>,
469 fn child_shape(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<Shape>;
470 fn format_children(&mut self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<()>;
471 fn format_last_child(
473 context: &RewriteContext<'_>,
477 fn join_rewrites(&self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<String>;
478 // Returns `Some` if the chain is only a root, None otherwise.
479 fn pure_root(&mut self) -> Option<String>;
482 // Data and behaviour that is shared by both chain formatters. The concrete
483 // formatters can delegate much behaviour to `ChainFormatterShared`.
484 struct ChainFormatterShared<'a> {
485 // The current working set of child items.
486 children: &'a [ChainItem],
487 // The current rewrites of items (includes trailing `?`s, but not any way to
488 // connect the rewrites together).
489 rewrites: Vec<String>,
490 // Whether the chain can fit on one line.
491 fits_single_line: bool,
492 // The number of children in the chain. This is not equal to `self.children.len()`
493 // because `self.children` will change size as we process the chain.
497 impl<'a> ChainFormatterShared<'a> {
498 fn new(chain: &'a Chain) -> ChainFormatterShared<'a> {
499 ChainFormatterShared {
500 children: &chain.children,
501 rewrites: Vec::with_capacity(chain.children.len() + 1),
502 fits_single_line: false,
503 child_count: chain.children.len(),
507 fn pure_root(&mut self) -> Option<String> {
508 if self.children.is_empty() {
509 assert_eq!(self.rewrites.len(), 1);
510 Some(self.rewrites.pop().unwrap())
516 // Rewrite the last child. The last child of a chain requires special treatment. We need to
517 // know whether 'overflowing' the last child make a better formatting:
519 // A chain with overflowing the last child:
521 // parent.child1.child2.last_child(
528 // A chain without overflowing the last child (in vertical layout):
533 // .last_child(a, b, c)
536 // In particular, overflowing is effective when the last child is a method with a multi-lined
537 // block-like argument (e.g. closure):
539 // parent.child1.child2.last_child(|a, b, c| {
540 // let x = foo(a, b, c);
541 // let y = bar(a, b, c);
548 fn format_last_child(
551 context: &RewriteContext<'_>,
555 let last = self.children.last()?;
556 let extendable = may_extend && last_line_extendable(&self.rewrites[0]);
557 let prev_last_line_width = last_line_width(&self.rewrites[0]);
559 // Total of all items excluding the last.
560 let almost_total = if extendable {
563 self.rewrites.iter().fold(0, |a, b| a + b.len())
565 let one_line_budget = if self.child_count == 1 {
568 min(shape.width, context.config.width_heuristics().chain_width)
570 .saturating_sub(almost_total);
572 let all_in_one_line = !self.children.iter().any(ChainItem::is_comment)
573 && self.rewrites.iter().all(|s| !s.contains('\n'))
574 && one_line_budget > 0;
575 let last_shape = if all_in_one_line {
576 shape.sub_width(last.tries)?
577 } else if extendable {
578 child_shape.sub_width(last.tries)?
580 child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?
583 let mut last_subexpr_str = None;
584 if all_in_one_line || extendable {
585 // First we try to 'overflow' the last child and see if it looks better than using
587 let one_line_shape = if context.use_block_indent() {
588 last_shape.offset_left(almost_total)
591 .visual_indent(almost_total)
592 .sub_width(almost_total)
595 if let Some(one_line_shape) = one_line_shape {
596 if let Some(rw) = last.rewrite(context, one_line_shape) {
597 // We allow overflowing here only if both of the following conditions match:
598 // 1. The entire chain fits in a single line except the last child.
599 // 2. `last_child_str.lines().count() >= 5`.
600 let line_count = rw.lines().count();
601 let could_fit_single_line = first_line_width(&rw) <= one_line_budget;
602 if could_fit_single_line && line_count >= 5 {
603 last_subexpr_str = Some(rw);
604 self.fits_single_line = all_in_one_line;
606 // We could not know whether overflowing is better than using vertical
607 // layout, just by looking at the overflowed rewrite. Now we rewrite the
608 // last child on its own line, and compare two rewrites to choose which is
610 let last_shape = child_shape
611 .sub_width(shape.rhs_overhead(context.config) + last.tries)?;
612 match last.rewrite(context, last_shape) {
613 Some(ref new_rw) if !could_fit_single_line => {
614 last_subexpr_str = Some(new_rw.clone());
616 Some(ref new_rw) if new_rw.lines().count() >= line_count => {
617 last_subexpr_str = Some(rw);
618 self.fits_single_line = could_fit_single_line && all_in_one_line;
620 new_rw @ Some(..) => {
621 last_subexpr_str = new_rw;
624 last_subexpr_str = Some(rw);
625 self.fits_single_line = could_fit_single_line && all_in_one_line;
633 let last_shape = if context.use_block_indent() {
636 child_shape.sub_width(shape.rhs_overhead(context.config) + last.tries)?
639 last_subexpr_str = last_subexpr_str.or_else(|| last.rewrite(context, last_shape));
640 self.rewrites.push(last_subexpr_str?);
644 fn join_rewrites(&self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<String> {
645 let connector = if self.fits_single_line {
646 // Yay, we can put everything on one line.
650 if *context.force_one_line_chain.borrow() {
653 child_shape.to_string_with_newline(context.config)
656 let mut rewrite_iter = self.rewrites.iter();
657 let mut result = rewrite_iter.next().unwrap().clone();
658 let children_iter = self.children.iter();
659 let iter = rewrite_iter.zip(children_iter);
661 for (rewrite, chain_item) in iter {
662 match chain_item.kind {
663 ChainItemKind::Comment(_, CommentPosition::Back) => result.push(' '),
664 ChainItemKind::Comment(_, CommentPosition::Top) => result.push_str(&connector),
665 _ => result.push_str(&connector),
667 result.push_str(&rewrite);
674 // Formats a chain using block indent.
675 struct ChainFormatterBlock<'a> {
676 shared: ChainFormatterShared<'a>,
677 root_ends_with_block: bool,
680 impl<'a> ChainFormatterBlock<'a> {
681 fn new(chain: &'a Chain) -> ChainFormatterBlock<'a> {
682 ChainFormatterBlock {
683 shared: ChainFormatterShared::new(chain),
684 root_ends_with_block: false,
689 impl<'a> ChainFormatter for ChainFormatterBlock<'a> {
693 context: &RewriteContext<'_>,
696 let mut root_rewrite: String = parent.rewrite(context, shape)?;
698 let mut root_ends_with_block = parent.kind.is_block_like(context, &root_rewrite);
699 let tab_width = context.config.tab_spaces().saturating_sub(shape.offset);
701 while root_rewrite.len() <= tab_width && !root_rewrite.contains('\n') {
702 let item = &self.shared.children[0];
703 if let ChainItemKind::Comment(..) = item.kind {
706 let shape = shape.offset_left(root_rewrite.len())?;
707 match &item.rewrite(context, shape) {
708 Some(rewrite) => root_rewrite.push_str(rewrite),
712 root_ends_with_block = last_line_extendable(&root_rewrite);
714 self.shared.children = &self.shared.children[1..];
715 if self.shared.children.is_empty() {
719 self.shared.rewrites.push(root_rewrite);
720 self.root_ends_with_block = root_ends_with_block;
724 fn child_shape(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<Shape> {
726 if self.root_ends_with_block {
727 shape.block_indent(0)
729 shape.block_indent(context.config.tab_spaces())
731 .with_max_width(context.config),
735 fn format_children(&mut self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<()> {
736 for item in &self.shared.children[..self.shared.children.len() - 1] {
737 let rewrite = item.rewrite(context, child_shape)?;
738 self.shared.rewrites.push(rewrite);
743 fn format_last_child(
745 context: &RewriteContext<'_>,
750 .format_last_child(true, context, shape, child_shape)
753 fn join_rewrites(&self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<String> {
754 self.shared.join_rewrites(context, child_shape)
757 fn pure_root(&mut self) -> Option<String> {
758 self.shared.pure_root()
762 // Format a chain using visual indent.
763 struct ChainFormatterVisual<'a> {
764 shared: ChainFormatterShared<'a>,
765 // The extra offset from the chain's shape to the position of the `.`
769 impl<'a> ChainFormatterVisual<'a> {
770 fn new(chain: &'a Chain) -> ChainFormatterVisual<'a> {
771 ChainFormatterVisual {
772 shared: ChainFormatterShared::new(chain),
778 impl<'a> ChainFormatter for ChainFormatterVisual<'a> {
782 context: &RewriteContext<'_>,
785 let parent_shape = shape.visual_indent(0);
786 let mut root_rewrite = parent.rewrite(context, parent_shape)?;
787 let multiline = root_rewrite.contains('\n');
788 self.offset = if multiline {
789 last_line_width(&root_rewrite).saturating_sub(shape.used_width())
791 trimmed_last_line_width(&root_rewrite)
794 if !multiline || parent.kind.is_block_like(context, &root_rewrite) {
795 let item = &self.shared.children[0];
796 if let ChainItemKind::Comment(..) = item.kind {
797 self.shared.rewrites.push(root_rewrite);
800 let child_shape = parent_shape
801 .visual_indent(self.offset)
802 .sub_width(self.offset)?;
803 let rewrite = item.rewrite(context, child_shape)?;
804 match wrap_str(rewrite, context.config.max_width(), shape) {
805 Some(rewrite) => root_rewrite.push_str(&rewrite),
807 // We couldn't fit in at the visual indent, try the last
809 let rewrite = item.rewrite(context, parent_shape)?;
810 root_rewrite.push_str(&rewrite);
815 self.shared.children = &self.shared.children[1..];
818 self.shared.rewrites.push(root_rewrite);
822 fn child_shape(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<Shape> {
824 .with_max_width(context.config)
825 .offset_left(self.offset)
826 .map(|s| s.visual_indent(0))
829 fn format_children(&mut self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<()> {
830 for item in &self.shared.children[..self.shared.children.len() - 1] {
831 let rewrite = item.rewrite(context, child_shape)?;
832 self.shared.rewrites.push(rewrite);
837 fn format_last_child(
839 context: &RewriteContext<'_>,
844 .format_last_child(false, context, shape, child_shape)
847 fn join_rewrites(&self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<String> {
848 self.shared.join_rewrites(context, child_shape)
851 fn pure_root(&mut self) -> Option<String> {
852 self.shared.pure_root()
856 /// Remove try operators (`?`s) that appear in the given string. If removing
857 /// them leaves an empty line, remove that line as well unless it is the first
858 /// line (we need the first newline for detecting pre/post comment).
859 fn trim_tries(s: &str) -> String {
860 let mut result = String::with_capacity(s.len());
861 let mut line_buffer = String::with_capacity(s.len());
862 for (kind, rich_char) in CharClasses::new(s.chars()) {
863 match rich_char.get_char() {
865 if result.is_empty() || !line_buffer.trim().is_empty() {
866 result.push_str(&line_buffer);
871 '?' if kind == FullCodeCharKind::Normal => continue,
872 c => line_buffer.push(c),
875 if !line_buffer.trim().is_empty() {
876 result.push_str(&line_buffer);