1 //! Format list-like expressions and items.
4 use std::iter::Peekable;
6 use rustc_span::BytePos;
8 use crate::comment::{find_comment_end, rewrite_comment, FindUncommented};
9 use crate::config::lists::*;
10 use crate::config::{Config, IndentStyle};
11 use crate::rewrite::RewriteContext;
12 use crate::shape::{Indent, Shape};
14 count_newlines, first_line_width, last_line_width, mk_sp, starts_with_newline,
17 use crate::visitor::SnippetProvider;
19 pub(crate) struct ListFormatting<'a> {
20 tactic: DefinitiveListTactic,
22 trailing_separator: SeparatorTactic,
23 separator_place: SeparatorPlace,
25 // Non-expressions, e.g., items, will have a new line at the end of the list.
26 // Important for comment styles.
27 ends_with_newline: bool,
28 // Remove newlines between list elements for expressions.
29 preserve_newline: bool,
30 // Nested import lists get some special handling for the "Mixed" list type
32 // Whether comments should be visually aligned.
37 impl<'a> ListFormatting<'a> {
38 pub(crate) fn new(shape: Shape, config: &'a Config) -> Self {
40 tactic: DefinitiveListTactic::Vertical,
42 trailing_separator: SeparatorTactic::Never,
43 separator_place: SeparatorPlace::Back,
45 ends_with_newline: true,
46 preserve_newline: false,
53 pub(crate) fn tactic(mut self, tactic: DefinitiveListTactic) -> Self {
58 pub(crate) fn separator(mut self, separator: &'a str) -> Self {
59 self.separator = separator;
63 pub(crate) fn trailing_separator(mut self, trailing_separator: SeparatorTactic) -> Self {
64 self.trailing_separator = trailing_separator;
68 pub(crate) fn separator_place(mut self, separator_place: SeparatorPlace) -> Self {
69 self.separator_place = separator_place;
73 pub(crate) fn ends_with_newline(mut self, ends_with_newline: bool) -> Self {
74 self.ends_with_newline = ends_with_newline;
78 pub(crate) fn preserve_newline(mut self, preserve_newline: bool) -> Self {
79 self.preserve_newline = preserve_newline;
83 pub(crate) fn nested(mut self, nested: bool) -> Self {
88 pub(crate) fn align_comments(mut self, align_comments: bool) -> Self {
89 self.align_comments = align_comments;
93 pub(crate) fn needs_trailing_separator(&self) -> bool {
94 match self.trailing_separator {
95 // We always put separator in front.
96 SeparatorTactic::Always => true,
97 SeparatorTactic::Vertical => self.tactic == DefinitiveListTactic::Vertical,
98 SeparatorTactic::Never => {
99 self.tactic == DefinitiveListTactic::Vertical && self.separator_place.is_front()
105 impl AsRef<ListItem> for ListItem {
106 fn as_ref(&self) -> &ListItem {
111 #[derive(PartialEq, Eq, Debug, Copy, Clone)]
112 pub(crate) enum ListItemCommentStyle {
113 // Try to keep the comment on the same line with the item.
115 // Put the comment on the previous or the next line of the item.
117 // No comment available.
121 #[derive(Debug, Clone)]
122 pub(crate) struct ListItem {
123 // None for comments mean that they are not present.
124 pub(crate) pre_comment: Option<String>,
125 pub(crate) pre_comment_style: ListItemCommentStyle,
126 // Item should include attributes and doc comments. None indicates a failed
128 pub(crate) item: Option<String>,
129 pub(crate) post_comment: Option<String>,
130 // Whether there is extra whitespace before this item.
131 pub(crate) new_lines: bool,
135 pub(crate) fn empty() -> ListItem {
138 pre_comment_style: ListItemCommentStyle::None,
145 pub(crate) fn inner_as_ref(&self) -> &str {
146 self.item.as_ref().map_or("", |s| s)
149 pub(crate) fn is_different_group(&self) -> bool {
150 self.inner_as_ref().contains('\n')
151 || self.pre_comment.is_some()
155 .map_or(false, |s| s.contains('\n'))
158 pub(crate) fn is_multiline(&self) -> bool {
159 self.inner_as_ref().contains('\n')
163 .map_or(false, |s| s.contains('\n'))
167 .map_or(false, |s| s.contains('\n'))
170 pub(crate) fn has_single_line_comment(&self) -> bool {
173 .map_or(false, |comment| comment.trim_start().starts_with("//"))
177 .map_or(false, |comment| comment.trim_start().starts_with("//"))
180 pub(crate) fn has_comment(&self) -> bool {
181 self.pre_comment.is_some() || self.post_comment.is_some()
184 pub(crate) fn from_str<S: Into<String>>(s: S) -> ListItem {
187 pre_comment_style: ListItemCommentStyle::None,
188 item: Some(s.into()),
194 // Returns `true` if the item causes something to be written.
195 fn is_substantial(&self) -> bool {
196 fn empty(s: &Option<String>) -> bool {
198 Some(ref s) if !s.is_empty() => false,
203 !(empty(&self.pre_comment) && empty(&self.item) && empty(&self.post_comment))
207 /// The type of separator for lists.
208 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
209 pub(crate) enum Separator {
215 pub(crate) fn len(self) -> usize {
218 Separator::Comma => 2,
220 Separator::VerticalBar => 3,
225 pub(crate) fn definitive_tactic<I, T>(
230 ) -> DefinitiveListTactic
232 I: IntoIterator<Item = T> + Clone,
235 let pre_line_comments = items
238 .any(|item| item.as_ref().has_single_line_comment());
240 let limit = match tactic {
241 _ if pre_line_comments => return DefinitiveListTactic::Vertical,
242 ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
243 ListTactic::Vertical => return DefinitiveListTactic::Vertical,
244 ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
245 ListTactic::Mixed | ListTactic::HorizontalVertical => width,
248 let (sep_count, total_width) = calculate_width(items.clone());
249 let total_sep_len = sep.len() * sep_count.saturating_sub(1);
250 let real_total = total_width + total_sep_len;
252 if real_total <= limit && !items.into_iter().any(|item| item.as_ref().is_multiline()) {
253 DefinitiveListTactic::Horizontal
256 ListTactic::Mixed => DefinitiveListTactic::Mixed,
257 _ => DefinitiveListTactic::Vertical,
262 // Format a list of commented items into a string.
263 pub(crate) fn write_list<I, T>(items: I, formatting: &ListFormatting<'_>) -> Option<String>
265 I: IntoIterator<Item = T> + Clone,
268 let tactic = formatting.tactic;
269 let sep_len = formatting.separator.len();
271 // Now that we know how we will layout, we can decide for sure if there
272 // will be a trailing separator.
273 let mut trailing_separator = formatting.needs_trailing_separator();
274 let mut result = String::with_capacity(128);
275 let cloned_items = items.clone();
276 let mut iter = items.into_iter().enumerate().peekable();
277 let mut item_max_width: Option<usize> = None;
279 SeparatorPlace::from_tactic(formatting.separator_place, tactic, formatting.separator);
280 let mut prev_item_had_post_comment = false;
281 let mut prev_item_is_nested_import = false;
283 let mut line_len = 0;
284 let indent_str = &formatting.shape.indent.to_string(formatting.config);
285 while let Some((i, item)) = iter.next() {
286 let item = item.as_ref();
287 let inner_item = item.item.as_ref()?;
289 let last = iter.peek().is_none();
290 let mut separate = match sep_place {
291 SeparatorPlace::Front => !first,
292 SeparatorPlace::Back => !last || trailing_separator,
294 let item_sep_len = if separate { sep_len } else { 0 };
296 // Item string may be multi-line. Its length (used for block comment alignment)
297 // should be only the length of the last line.
298 let item_last_line = if item.is_multiline() {
299 inner_item.lines().last().unwrap_or("")
303 let mut item_last_line_width = item_last_line.len() + item_sep_len;
304 if item_last_line.starts_with(&**indent_str) {
305 item_last_line_width -= indent_str.len();
308 if !item.is_substantial() {
313 DefinitiveListTactic::Horizontal if !first => {
316 DefinitiveListTactic::SpecialMacro(num_args_before) => {
319 } else if i < num_args_before {
321 } else if i <= num_args_before + 1 {
323 result.push_str(indent_str);
328 DefinitiveListTactic::Vertical
329 if !first && !inner_item.is_empty() && !result.is_empty() =>
332 result.push_str(indent_str);
334 DefinitiveListTactic::Mixed => {
335 let total_width = total_item_width(item) + item_sep_len;
337 // 1 is space between separator and item.
338 if (line_len > 0 && line_len + 1 + total_width > formatting.shape.width)
339 || prev_item_had_post_comment
340 || (formatting.nested
341 && (prev_item_is_nested_import || (!first && inner_item.contains("::"))))
344 result.push_str(indent_str);
346 if formatting.ends_with_newline {
347 trailing_separator = true;
349 } else if line_len > 0 {
354 if last && formatting.ends_with_newline {
355 separate = formatting.trailing_separator != SeparatorTactic::Never;
358 line_len += total_width;
364 if let Some(ref comment) = item.pre_comment {
365 // Block style in non-vertical mode.
366 let block_mode = tactic == DefinitiveListTactic::Horizontal;
367 // Width restriction is only relevant in vertical mode.
369 rewrite_comment(comment, block_mode, formatting.shape, formatting.config)?;
370 result.push_str(&comment);
372 if !inner_item.is_empty() {
373 if tactic == DefinitiveListTactic::Vertical || tactic == DefinitiveListTactic::Mixed
375 // We cannot keep pre-comments on the same line if the comment if normalized.
376 let keep_comment = if formatting.config.normalize_comments()
377 || item.pre_comment_style == ListItemCommentStyle::DifferentLine
381 // We will try to keep the comment on the same line with the item here.
383 let total_width = total_item_width(item) + item_sep_len + 1;
384 total_width <= formatting.shape.width
390 result.push_str(indent_str);
391 // This is the width of the item (without comments).
392 line_len = item.item.as_ref().map_or(0, |s| unicode_str_width(&s));
398 item_max_width = None;
401 if separate && sep_place.is_front() && !first {
402 result.push_str(formatting.separator.trim());
405 result.push_str(inner_item);
408 if tactic == DefinitiveListTactic::Horizontal && item.post_comment.is_some() {
409 let comment = item.post_comment.as_ref().unwrap();
410 let formatted_comment = rewrite_comment(
413 Shape::legacy(formatting.shape.width, Indent::empty()),
418 result.push_str(&formatted_comment);
421 if separate && sep_place.is_back() {
422 result.push_str(formatting.separator);
425 if tactic != DefinitiveListTactic::Horizontal && item.post_comment.is_some() {
426 let comment = item.post_comment.as_ref().unwrap();
427 let overhead = last_line_width(&result) + first_line_width(comment.trim());
429 let rewrite_post_comment = |item_max_width: &mut Option<usize>| {
430 if item_max_width.is_none() && !last && !inner_item.contains('\n') {
431 *item_max_width = Some(max_width_of_item_with_post_comment(
435 formatting.config.max_width(),
438 let overhead = if starts_with_newline(comment) {
440 } else if let Some(max_width) = *item_max_width {
443 // 1 = space between item and comment.
444 item_last_line_width + 1
446 let width = formatting.shape.width.checked_sub(overhead).unwrap_or(1);
447 let offset = formatting.shape.indent + overhead;
448 let comment_shape = Shape::legacy(width, offset);
450 // Use block-style only for the last item or multiline comments.
451 let block_style = !formatting.ends_with_newline && last
452 || comment.trim().contains('\n')
453 || comment.trim().len() > width;
456 comment.trim_start(),
463 let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?;
465 if !starts_with_newline(comment) {
466 if formatting.align_comments {
467 let mut comment_alignment =
468 post_comment_alignment(item_max_width, inner_item.len());
469 if first_line_width(&formatted_comment)
470 + last_line_width(&result)
473 > formatting.config.max_width()
475 item_max_width = None;
476 formatted_comment = rewrite_post_comment(&mut item_max_width)?;
478 post_comment_alignment(item_max_width, inner_item.len());
480 for _ in 0..=comment_alignment {
484 // An additional space for the missing trailing separator (or
485 // if we skipped alignment above).
486 if !formatting.align_comments
488 && item_max_width.is_some()
490 && !formatting.separator.is_empty())
496 result.push_str(indent_str);
498 if formatted_comment.contains('\n') {
499 item_max_width = None;
501 result.push_str(&formatted_comment);
503 item_max_width = None;
506 if formatting.preserve_newline
508 && tactic == DefinitiveListTactic::Vertical
511 item_max_width = None;
515 prev_item_had_post_comment = item.post_comment.is_some();
516 prev_item_is_nested_import = inner_item.contains("::");
522 fn max_width_of_item_with_post_comment<I, T>(
529 I: IntoIterator<Item = T> + Clone,
532 let mut max_width = 0;
533 let mut first = true;
534 for item in items.clone().into_iter().skip(i) {
535 let item = item.as_ref();
536 let inner_item_width = item.inner_as_ref().len();
538 && (item.is_different_group()
539 || item.post_comment.is_none()
540 || inner_item_width + overhead > max_budget)
544 if max_width < inner_item_width {
545 max_width = inner_item_width;
555 fn post_comment_alignment(item_max_width: Option<usize>, inner_item_len: usize) -> usize {
556 item_max_width.unwrap_or(0).saturating_sub(inner_item_len)
559 pub(crate) struct ListItems<'a, I, F1, F2, F3>
563 snippet_provider: &'a SnippetProvider,
568 prev_span_end: BytePos,
569 next_span_start: BytePos,
575 pub(crate) fn extract_pre_comment(pre_snippet: &str) -> (Option<String>, ListItemCommentStyle) {
576 let trimmed_pre_snippet = pre_snippet.trim();
577 // Both start and end are checked to support keeping a block comment inline with
578 // the item, even if there are preceeding line comments, while still supporting
579 // a snippet that starts with a block comment but also contains one or more
580 // trailing single line comments.
581 // https://github.com/rust-lang/rustfmt/issues/3025
582 // https://github.com/rust-lang/rustfmt/pull/3048
583 // https://github.com/rust-lang/rustfmt/issues/3839
584 let starts_with_block_comment = trimmed_pre_snippet.starts_with("/*");
585 let ends_with_block_comment = trimmed_pre_snippet.ends_with("*/");
586 let starts_with_single_line_comment = trimmed_pre_snippet.starts_with("//");
587 if ends_with_block_comment {
588 let comment_end = pre_snippet.rfind(|c| c == '/').unwrap();
589 if pre_snippet[comment_end..].contains('\n') {
591 Some(trimmed_pre_snippet.to_owned()),
592 ListItemCommentStyle::DifferentLine,
596 Some(trimmed_pre_snippet.to_owned()),
597 ListItemCommentStyle::SameLine,
600 } else if starts_with_single_line_comment || starts_with_block_comment {
602 Some(trimmed_pre_snippet.to_owned()),
603 ListItemCommentStyle::DifferentLine,
606 (None, ListItemCommentStyle::None)
610 pub(crate) fn extract_post_comment(
614 ) -> Option<String> {
615 let white_space: &[_] = &[' ', '\t'];
617 // Cleanup post-comment: strip separators and whitespace.
618 let post_snippet = post_snippet[..comment_end].trim();
619 let post_snippet_trimmed = if post_snippet.starts_with(|c| c == ',' || c == ':') {
620 post_snippet[1..].trim_matches(white_space)
621 } else if post_snippet.starts_with(separator) {
622 post_snippet[separator.len()..].trim_matches(white_space)
624 // not comment or over two lines
625 else if post_snippet.ends_with(',')
626 && (!post_snippet.trim().starts_with("//") || post_snippet.trim().contains('\n'))
628 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
632 // FIXME(#3441): post_snippet includes 'const' now
633 // it should not include here
634 let removed_newline_snippet = post_snippet_trimmed.trim();
635 if !post_snippet_trimmed.is_empty()
636 && (removed_newline_snippet.starts_with("//") || removed_newline_snippet.starts_with("/*"))
638 Some(post_snippet_trimmed.to_owned())
644 pub(crate) fn get_comment_end(
652 .find_uncommented(terminator)
653 .unwrap_or_else(|| post_snippet.len());
656 let mut block_open_index = post_snippet.find("/*");
657 // check if it really is a block comment (and not `//*` or a nested comment)
658 if let Some(i) = block_open_index {
659 match post_snippet.find('/') {
660 Some(j) if j < i => block_open_index = None,
661 _ if post_snippet[..i].ends_with('/') => block_open_index = None,
665 let newline_index = post_snippet.find('\n');
666 if let Some(separator_index) = post_snippet.find_uncommented(separator) {
667 match (block_open_index, newline_index) {
668 // Separator before comment, with the next item on same line.
669 // Comment belongs to next item.
670 (Some(i), None) if i > separator_index => separator_index + 1,
671 // Block-style post-comment before the separator.
672 (Some(i), None) => cmp::max(
673 find_comment_end(&post_snippet[i..]).unwrap() + i,
676 // Block-style post-comment. Either before or after the separator.
677 (Some(i), Some(j)) if i < j => cmp::max(
678 find_comment_end(&post_snippet[i..]).unwrap() + i,
681 // Potential *single* line comment.
682 (_, Some(j)) if j > separator_index => j + 1,
683 _ => post_snippet.len(),
685 } else if let Some(newline_index) = newline_index {
686 // Match arms may not have trailing comma. In any case, for match arms,
687 // we will assume that the post comment belongs to the next arm if they
688 // do not end with trailing comma.
695 // Account for extra whitespace between items. This is fiddly
696 // because of the way we divide pre- and post- comments.
697 pub(crate) fn has_extra_newline(post_snippet: &str, comment_end: usize) -> bool {
698 if post_snippet.is_empty() || comment_end == 0 {
702 let len_last = post_snippet[..comment_end]
707 // Everything from the separator to the next item.
708 let test_snippet = &post_snippet[comment_end - len_last..];
709 let first_newline = test_snippet
711 .unwrap_or_else(|| test_snippet.len());
712 // From the end of the first line of comments.
713 let test_snippet = &test_snippet[first_newline..];
714 let first = test_snippet
715 .find(|c: char| !c.is_whitespace())
716 .unwrap_or_else(|| test_snippet.len());
717 // From the end of the first line of comments to the next non-whitespace char.
718 let test_snippet = &test_snippet[..first];
720 // There were multiple line breaks which got trimmed to nothing.
721 count_newlines(test_snippet) > 1
724 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
726 I: Iterator<Item = T>,
727 F1: Fn(&T) -> BytePos,
728 F2: Fn(&T) -> BytePos,
729 F3: Fn(&T) -> Option<String>,
731 type Item = ListItem;
733 fn next(&mut self) -> Option<Self::Item> {
734 self.inner.next().map(|item| {
736 let pre_snippet = self
738 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
740 let (pre_comment, pre_comment_style) = extract_pre_comment(pre_snippet);
743 let next_start = match self.inner.peek() {
744 Some(next_item) => (self.get_lo)(next_item),
745 None => self.next_span_start,
747 let post_snippet = self
749 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
751 let comment_end = get_comment_end(
755 self.inner.peek().is_none(),
757 let new_lines = has_extra_newline(post_snippet, comment_end);
758 let post_comment = extract_post_comment(post_snippet, comment_end, self.separator);
760 self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
765 item: if self.inner.peek().is_none() && self.leave_last {
768 (self.get_item_string)(&item)
777 #[allow(clippy::too_many_arguments)]
778 // Creates an iterator over a list's items with associated comments.
779 pub(crate) fn itemize_list<'a, T, I, F1, F2, F3>(
780 snippet_provider: &'a SnippetProvider,
787 prev_span_end: BytePos,
788 next_span_start: BytePos,
790 ) -> ListItems<'a, I, F1, F2, F3>
792 I: Iterator<Item = T>,
793 F1: Fn(&T) -> BytePos,
794 F2: Fn(&T) -> BytePos,
795 F3: Fn(&T) -> Option<String>,
799 inner: inner.peekable(),
811 /// Returns the count and total width of the list items.
812 fn calculate_width<I, T>(items: I) -> (usize, usize)
814 I: IntoIterator<Item = T>,
819 .map(|item| total_item_width(item.as_ref()))
820 .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
823 pub(crate) fn total_item_width(item: &ListItem) -> usize {
824 comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
825 + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
826 + &item.item.as_ref().map_or(0, |s| unicode_str_width(&s))
829 fn comment_len(comment: Option<&str>) -> usize {
832 let text_len = s.trim().len();
834 // We'll put " /*" before and " */" after inline comments.
844 // Compute horizontal and vertical shapes for a struct-lit-like thing.
845 pub(crate) fn struct_lit_shape(
847 context: &RewriteContext<'_>,
850 ) -> Option<(Option<Shape>, Shape)> {
851 let v_shape = match context.config.indent_style() {
852 IndentStyle::Visual => shape
854 .shrink_left(prefix_width)?
855 .sub_width(suffix_width)?,
856 IndentStyle::Block => {
857 let shape = shape.block_indent(context.config.tab_spaces());
859 width: context.budget(shape.indent.width()),
864 let shape_width = shape.width.checked_sub(prefix_width + suffix_width);
865 if let Some(w) = shape_width {
866 let shape_width = cmp::min(w, context.config.struct_lit_width());
867 Some((Some(Shape::legacy(shape_width, shape.indent)), v_shape))
869 Some((None, v_shape))
873 // Compute the tactic for the internals of a struct-lit-like thing.
874 pub(crate) fn struct_lit_tactic(
875 h_shape: Option<Shape>,
876 context: &RewriteContext<'_>,
878 ) -> DefinitiveListTactic {
879 if let Some(h_shape) = h_shape {
880 let prelim_tactic = match (context.config.indent_style(), items.len()) {
881 (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
882 _ if context.config.struct_lit_single_line() => ListTactic::HorizontalVertical,
883 _ => ListTactic::Vertical,
885 definitive_tactic(items, prelim_tactic, Separator::Comma, h_shape.width)
887 DefinitiveListTactic::Vertical
891 // Given a tactic and possible shapes for horizontal and vertical layout,
892 // come up with the actual shape to use.
893 pub(crate) fn shape_for_tactic(
894 tactic: DefinitiveListTactic,
895 h_shape: Option<Shape>,
899 DefinitiveListTactic::Horizontal => h_shape.unwrap(),
904 // Create a ListFormatting object for formatting the internals of a
905 // struct-lit-like thing, that is a series of fields.
906 pub(crate) fn struct_lit_formatting<'a>(
908 tactic: DefinitiveListTactic,
909 context: &'a RewriteContext<'_>,
910 force_no_trailing_comma: bool,
911 ) -> ListFormatting<'a> {
912 let ends_with_newline = context.config.indent_style() != IndentStyle::Visual
913 && tactic == DefinitiveListTactic::Vertical;
917 trailing_separator: if force_no_trailing_comma {
918 SeparatorTactic::Never
920 context.config.trailing_comma()
922 separator_place: SeparatorPlace::Back,
925 preserve_newline: true,
927 align_comments: true,
928 config: context.config,