]> git.lizzy.rs Git - rust.git/blob - src/lists.rs
Determine when new comment lines are needed for itemized blocks
[rust.git] / src / lists.rs
1 //! Format list-like expressions and items.
2
3 use std::cmp;
4 use std::iter::Peekable;
5
6 use rustc_span::BytePos;
7
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};
13 use crate::utils::{
14     count_newlines, first_line_width, last_line_width, mk_sp, starts_with_newline,
15     unicode_str_width,
16 };
17 use crate::visitor::SnippetProvider;
18
19 pub(crate) struct ListFormatting<'a> {
20     tactic: DefinitiveListTactic,
21     separator: &'a str,
22     trailing_separator: SeparatorTactic,
23     separator_place: SeparatorPlace,
24     shape: Shape,
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
31     nested: bool,
32     // Whether comments should be visually aligned.
33     align_comments: bool,
34     config: &'a Config,
35 }
36
37 impl<'a> ListFormatting<'a> {
38     pub(crate) fn new(shape: Shape, config: &'a Config) -> Self {
39         ListFormatting {
40             tactic: DefinitiveListTactic::Vertical,
41             separator: ",",
42             trailing_separator: SeparatorTactic::Never,
43             separator_place: SeparatorPlace::Back,
44             shape,
45             ends_with_newline: true,
46             preserve_newline: false,
47             nested: false,
48             align_comments: true,
49             config,
50         }
51     }
52
53     pub(crate) fn tactic(mut self, tactic: DefinitiveListTactic) -> Self {
54         self.tactic = tactic;
55         self
56     }
57
58     pub(crate) fn separator(mut self, separator: &'a str) -> Self {
59         self.separator = separator;
60         self
61     }
62
63     pub(crate) fn trailing_separator(mut self, trailing_separator: SeparatorTactic) -> Self {
64         self.trailing_separator = trailing_separator;
65         self
66     }
67
68     pub(crate) fn separator_place(mut self, separator_place: SeparatorPlace) -> Self {
69         self.separator_place = separator_place;
70         self
71     }
72
73     pub(crate) fn ends_with_newline(mut self, ends_with_newline: bool) -> Self {
74         self.ends_with_newline = ends_with_newline;
75         self
76     }
77
78     pub(crate) fn preserve_newline(mut self, preserve_newline: bool) -> Self {
79         self.preserve_newline = preserve_newline;
80         self
81     }
82
83     pub(crate) fn nested(mut self, nested: bool) -> Self {
84         self.nested = nested;
85         self
86     }
87
88     pub(crate) fn align_comments(mut self, align_comments: bool) -> Self {
89         self.align_comments = align_comments;
90         self
91     }
92
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()
100             }
101         }
102     }
103 }
104
105 impl AsRef<ListItem> for ListItem {
106     fn as_ref(&self) -> &ListItem {
107         self
108     }
109 }
110
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.
114     SameLine,
115     // Put the comment on the previous or the next line of the item.
116     DifferentLine,
117     // No comment available.
118     None,
119 }
120
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
127     // rewrite.
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,
132 }
133
134 impl ListItem {
135     pub(crate) fn empty() -> ListItem {
136         ListItem {
137             pre_comment: None,
138             pre_comment_style: ListItemCommentStyle::None,
139             item: None,
140             post_comment: None,
141             new_lines: false,
142         }
143     }
144
145     pub(crate) fn inner_as_ref(&self) -> &str {
146         self.item.as_ref().map_or("", |s| s)
147     }
148
149     pub(crate) fn is_different_group(&self) -> bool {
150         self.inner_as_ref().contains('\n')
151             || self.pre_comment.is_some()
152             || self
153                 .post_comment
154                 .as_ref()
155                 .map_or(false, |s| s.contains('\n'))
156     }
157
158     pub(crate) fn is_multiline(&self) -> bool {
159         self.inner_as_ref().contains('\n')
160             || self
161                 .pre_comment
162                 .as_ref()
163                 .map_or(false, |s| s.contains('\n'))
164             || self
165                 .post_comment
166                 .as_ref()
167                 .map_or(false, |s| s.contains('\n'))
168     }
169
170     pub(crate) fn has_single_line_comment(&self) -> bool {
171         self.pre_comment
172             .as_ref()
173             .map_or(false, |comment| comment.trim_start().starts_with("//"))
174             || self
175                 .post_comment
176                 .as_ref()
177                 .map_or(false, |comment| comment.trim_start().starts_with("//"))
178     }
179
180     pub(crate) fn has_comment(&self) -> bool {
181         self.pre_comment.is_some() || self.post_comment.is_some()
182     }
183
184     pub(crate) fn from_str<S: Into<String>>(s: S) -> ListItem {
185         ListItem {
186             pre_comment: None,
187             pre_comment_style: ListItemCommentStyle::None,
188             item: Some(s.into()),
189             post_comment: None,
190             new_lines: false,
191         }
192     }
193
194     // Returns `true` if the item causes something to be written.
195     fn is_substantial(&self) -> bool {
196         fn empty(s: &Option<String>) -> bool {
197             !matches!(*s, Some(ref s) if !s.is_empty())
198         }
199
200         !(empty(&self.pre_comment) && empty(&self.item) && empty(&self.post_comment))
201     }
202 }
203
204 /// The type of separator for lists.
205 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
206 pub(crate) enum Separator {
207     Comma,
208     VerticalBar,
209 }
210
211 impl Separator {
212     pub(crate) fn len(self) -> usize {
213         match self {
214             // 2 = `, `
215             Separator::Comma => 2,
216             // 3 = ` | `
217             Separator::VerticalBar => 3,
218         }
219     }
220 }
221
222 pub(crate) fn definitive_tactic<I, T>(
223     items: I,
224     tactic: ListTactic,
225     sep: Separator,
226     width: usize,
227 ) -> DefinitiveListTactic
228 where
229     I: IntoIterator<Item = T> + Clone,
230     T: AsRef<ListItem>,
231 {
232     let pre_line_comments = items
233         .clone()
234         .into_iter()
235         .any(|item| item.as_ref().has_single_line_comment());
236
237     let limit = match tactic {
238         _ if pre_line_comments => return DefinitiveListTactic::Vertical,
239         ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
240         ListTactic::Vertical => return DefinitiveListTactic::Vertical,
241         ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
242         ListTactic::Mixed | ListTactic::HorizontalVertical => width,
243     };
244
245     let (sep_count, total_width) = calculate_width(items.clone());
246     let total_sep_len = sep.len() * sep_count.saturating_sub(1);
247     let real_total = total_width + total_sep_len;
248
249     if real_total <= limit && !items.into_iter().any(|item| item.as_ref().is_multiline()) {
250         DefinitiveListTactic::Horizontal
251     } else {
252         match tactic {
253             ListTactic::Mixed => DefinitiveListTactic::Mixed,
254             _ => DefinitiveListTactic::Vertical,
255         }
256     }
257 }
258
259 // Format a list of commented items into a string.
260 pub(crate) fn write_list<I, T>(items: I, formatting: &ListFormatting<'_>) -> Option<String>
261 where
262     I: IntoIterator<Item = T> + Clone,
263     T: AsRef<ListItem>,
264 {
265     let tactic = formatting.tactic;
266     let sep_len = formatting.separator.len();
267
268     // Now that we know how we will layout, we can decide for sure if there
269     // will be a trailing separator.
270     let mut trailing_separator = formatting.needs_trailing_separator();
271     let mut result = String::with_capacity(128);
272     let cloned_items = items.clone();
273     let mut iter = items.into_iter().enumerate().peekable();
274     let mut item_max_width: Option<usize> = None;
275     let sep_place =
276         SeparatorPlace::from_tactic(formatting.separator_place, tactic, formatting.separator);
277     let mut prev_item_had_post_comment = false;
278     let mut prev_item_is_nested_import = false;
279
280     let mut line_len = 0;
281     let indent_str = &formatting.shape.indent.to_string(formatting.config);
282     while let Some((i, item)) = iter.next() {
283         let item = item.as_ref();
284         let inner_item = item.item.as_ref()?;
285         let first = i == 0;
286         let last = iter.peek().is_none();
287         let mut separate = match sep_place {
288             SeparatorPlace::Front => !first,
289             SeparatorPlace::Back => !last || trailing_separator,
290         };
291         let item_sep_len = if separate { sep_len } else { 0 };
292
293         // Item string may be multi-line. Its length (used for block comment alignment)
294         // should be only the length of the last line.
295         let item_last_line = if item.is_multiline() {
296             inner_item.lines().last().unwrap_or("")
297         } else {
298             inner_item.as_ref()
299         };
300         let mut item_last_line_width = item_last_line.len() + item_sep_len;
301         if item_last_line.starts_with(&**indent_str) {
302             item_last_line_width -= indent_str.len();
303         }
304
305         if !item.is_substantial() {
306             continue;
307         }
308
309         match tactic {
310             DefinitiveListTactic::Horizontal if !first => {
311                 result.push(' ');
312             }
313             DefinitiveListTactic::SpecialMacro(num_args_before) => {
314                 if i == 0 {
315                     // Nothing
316                 } else if i < num_args_before {
317                     result.push(' ');
318                 } else if i <= num_args_before + 1 {
319                     result.push('\n');
320                     result.push_str(indent_str);
321                 } else {
322                     result.push(' ');
323                 }
324             }
325             DefinitiveListTactic::Vertical
326                 if !first && !inner_item.is_empty() && !result.is_empty() =>
327             {
328                 result.push('\n');
329                 result.push_str(indent_str);
330             }
331             DefinitiveListTactic::Mixed => {
332                 let total_width = total_item_width(item) + item_sep_len;
333
334                 // 1 is space between separator and item.
335                 if (line_len > 0 && line_len + 1 + total_width > formatting.shape.width)
336                     || prev_item_had_post_comment
337                     || (formatting.nested
338                         && (prev_item_is_nested_import || (!first && inner_item.contains("::"))))
339                 {
340                     result.push('\n');
341                     result.push_str(indent_str);
342                     line_len = 0;
343                     if formatting.ends_with_newline {
344                         trailing_separator = true;
345                     }
346                 } else if line_len > 0 {
347                     result.push(' ');
348                     line_len += 1;
349                 }
350
351                 if last && formatting.ends_with_newline {
352                     separate = formatting.trailing_separator != SeparatorTactic::Never;
353                 }
354
355                 line_len += total_width;
356             }
357             _ => {}
358         }
359
360         // Pre-comments
361         if let Some(ref comment) = item.pre_comment {
362             // Block style in non-vertical mode.
363             let block_mode = tactic == DefinitiveListTactic::Horizontal;
364             // Width restriction is only relevant in vertical mode.
365             let comment =
366                 rewrite_comment(comment, block_mode, formatting.shape, formatting.config)?;
367             result.push_str(&comment);
368
369             if !inner_item.is_empty() {
370                 use DefinitiveListTactic::*;
371                 if matches!(tactic, Vertical | Mixed | SpecialMacro(_)) {
372                     // We cannot keep pre-comments on the same line if the comment is normalized.
373                     let keep_comment = if formatting.config.normalize_comments()
374                         || item.pre_comment_style == ListItemCommentStyle::DifferentLine
375                     {
376                         false
377                     } else {
378                         // We will try to keep the comment on the same line with the item here.
379                         // 1 = ` `
380                         let total_width = total_item_width(item) + item_sep_len + 1;
381                         total_width <= formatting.shape.width
382                     };
383                     if keep_comment {
384                         result.push(' ');
385                     } else {
386                         result.push('\n');
387                         result.push_str(indent_str);
388                         // This is the width of the item (without comments).
389                         line_len = item.item.as_ref().map_or(0, |s| unicode_str_width(s));
390                     }
391                 } else {
392                     result.push(' ')
393                 }
394             }
395             item_max_width = None;
396         }
397
398         if separate && sep_place.is_front() && !first {
399             result.push_str(formatting.separator.trim());
400             result.push(' ');
401         }
402         result.push_str(inner_item);
403
404         // Post-comments
405         if tactic == DefinitiveListTactic::Horizontal && item.post_comment.is_some() {
406             let comment = item.post_comment.as_ref().unwrap();
407             let formatted_comment = rewrite_comment(
408                 comment,
409                 true,
410                 Shape::legacy(formatting.shape.width, Indent::empty()),
411                 formatting.config,
412             )?;
413
414             result.push(' ');
415             result.push_str(&formatted_comment);
416         }
417
418         if separate && sep_place.is_back() {
419             result.push_str(formatting.separator);
420         }
421
422         if tactic != DefinitiveListTactic::Horizontal && item.post_comment.is_some() {
423             let comment = item.post_comment.as_ref().unwrap();
424             let overhead = last_line_width(&result) + first_line_width(comment.trim());
425
426             let rewrite_post_comment = |item_max_width: &mut Option<usize>| {
427                 if item_max_width.is_none() && !last && !inner_item.contains('\n') {
428                     *item_max_width = Some(max_width_of_item_with_post_comment(
429                         &cloned_items,
430                         i,
431                         overhead,
432                         formatting.config.max_width(),
433                     ));
434                 }
435                 let overhead = if starts_with_newline(comment) {
436                     0
437                 } else if let Some(max_width) = *item_max_width {
438                     max_width + 2
439                 } else {
440                     // 1 = space between item and comment.
441                     item_last_line_width + 1
442                 };
443                 let width = formatting.shape.width.checked_sub(overhead).unwrap_or(1);
444                 let offset = formatting.shape.indent + overhead;
445                 let comment_shape = Shape::legacy(width, offset);
446
447                 let block_style = if !formatting.ends_with_newline && last {
448                     true
449                 } else if starts_with_newline(comment) {
450                     false
451                 } else if comment.trim().contains('\n') || comment.trim().len() > width {
452                     true
453                 } else {
454                     false
455                 };
456
457                 rewrite_comment(
458                     comment.trim_start(),
459                     block_style,
460                     comment_shape,
461                     formatting.config,
462                 )
463             };
464
465             let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?;
466
467             if !starts_with_newline(comment) {
468                 if formatting.align_comments {
469                     let mut comment_alignment =
470                         post_comment_alignment(item_max_width, inner_item.len());
471                     if first_line_width(&formatted_comment)
472                         + last_line_width(&result)
473                         + comment_alignment
474                         + 1
475                         > formatting.config.max_width()
476                     {
477                         item_max_width = None;
478                         formatted_comment = rewrite_post_comment(&mut item_max_width)?;
479                         comment_alignment =
480                             post_comment_alignment(item_max_width, inner_item.len());
481                     }
482                     for _ in 0..=comment_alignment {
483                         result.push(' ');
484                     }
485                 }
486                 // An additional space for the missing trailing separator (or
487                 // if we skipped alignment above).
488                 if !formatting.align_comments
489                     || (last
490                         && item_max_width.is_some()
491                         && !separate
492                         && !formatting.separator.is_empty())
493                 {
494                     result.push(' ');
495                 }
496             } else {
497                 result.push('\n');
498                 result.push_str(indent_str);
499             }
500             if formatted_comment.contains('\n') {
501                 item_max_width = None;
502             }
503             result.push_str(&formatted_comment);
504         } else {
505             item_max_width = None;
506         }
507
508         if formatting.preserve_newline
509             && !last
510             && tactic == DefinitiveListTactic::Vertical
511             && item.new_lines
512         {
513             item_max_width = None;
514             result.push('\n');
515         }
516
517         prev_item_had_post_comment = item.post_comment.is_some();
518         prev_item_is_nested_import = inner_item.contains("::");
519     }
520
521     Some(result)
522 }
523
524 fn max_width_of_item_with_post_comment<I, T>(
525     items: &I,
526     i: usize,
527     overhead: usize,
528     max_budget: usize,
529 ) -> usize
530 where
531     I: IntoIterator<Item = T> + Clone,
532     T: AsRef<ListItem>,
533 {
534     let mut max_width = 0;
535     let mut first = true;
536     for item in items.clone().into_iter().skip(i) {
537         let item = item.as_ref();
538         let inner_item_width = item.inner_as_ref().len();
539         if !first
540             && (item.is_different_group()
541                 || item.post_comment.is_none()
542                 || inner_item_width + overhead > max_budget)
543         {
544             return max_width;
545         }
546         if max_width < inner_item_width {
547             max_width = inner_item_width;
548         }
549         if item.new_lines {
550             return max_width;
551         }
552         first = false;
553     }
554     max_width
555 }
556
557 fn post_comment_alignment(item_max_width: Option<usize>, inner_item_len: usize) -> usize {
558     item_max_width.unwrap_or(0).saturating_sub(inner_item_len)
559 }
560
561 pub(crate) struct ListItems<'a, I, F1, F2, F3>
562 where
563     I: Iterator,
564 {
565     snippet_provider: &'a SnippetProvider,
566     inner: Peekable<I>,
567     get_lo: F1,
568     get_hi: F2,
569     get_item_string: F3,
570     prev_span_end: BytePos,
571     next_span_start: BytePos,
572     terminator: &'a str,
573     separator: &'a str,
574     leave_last: bool,
575 }
576
577 pub(crate) fn extract_pre_comment(pre_snippet: &str) -> (Option<String>, ListItemCommentStyle) {
578     let trimmed_pre_snippet = pre_snippet.trim();
579     // Both start and end are checked to support keeping a block comment inline with
580     // the item, even if there are preceeding line comments, while still supporting
581     // a snippet that starts with a block comment but also contains one or more
582     // trailing single line comments.
583     // https://github.com/rust-lang/rustfmt/issues/3025
584     // https://github.com/rust-lang/rustfmt/pull/3048
585     // https://github.com/rust-lang/rustfmt/issues/3839
586     let starts_with_block_comment = trimmed_pre_snippet.starts_with("/*");
587     let ends_with_block_comment = trimmed_pre_snippet.ends_with("*/");
588     let starts_with_single_line_comment = trimmed_pre_snippet.starts_with("//");
589     if ends_with_block_comment {
590         let comment_end = pre_snippet.rfind(|c| c == '/').unwrap();
591         if pre_snippet[comment_end..].contains('\n') {
592             (
593                 Some(trimmed_pre_snippet.to_owned()),
594                 ListItemCommentStyle::DifferentLine,
595             )
596         } else {
597             (
598                 Some(trimmed_pre_snippet.to_owned()),
599                 ListItemCommentStyle::SameLine,
600             )
601         }
602     } else if starts_with_single_line_comment || starts_with_block_comment {
603         (
604             Some(trimmed_pre_snippet.to_owned()),
605             ListItemCommentStyle::DifferentLine,
606         )
607     } else {
608         (None, ListItemCommentStyle::None)
609     }
610 }
611
612 pub(crate) fn extract_post_comment(
613     post_snippet: &str,
614     comment_end: usize,
615     separator: &str,
616 ) -> Option<String> {
617     let white_space: &[_] = &[' ', '\t'];
618
619     // Cleanup post-comment: strip separators and whitespace.
620     let post_snippet = post_snippet[..comment_end].trim();
621     let post_snippet_trimmed = if post_snippet.starts_with(|c| c == ',' || c == ':') {
622         post_snippet[1..].trim_matches(white_space)
623     } else if let Some(stripped) = post_snippet.strip_prefix(separator) {
624         stripped.trim_matches(white_space)
625     }
626     // not comment or over two lines
627     else if post_snippet.ends_with(',')
628         && (!post_snippet.trim().starts_with("//") || post_snippet.trim().contains('\n'))
629     {
630         post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
631     } else {
632         post_snippet
633     };
634     // FIXME(#3441): post_snippet includes 'const' now
635     // it should not include here
636     let removed_newline_snippet = post_snippet_trimmed.trim();
637     if !post_snippet_trimmed.is_empty()
638         && (removed_newline_snippet.starts_with("//") || removed_newline_snippet.starts_with("/*"))
639     {
640         Some(post_snippet_trimmed.to_owned())
641     } else {
642         None
643     }
644 }
645
646 pub(crate) fn get_comment_end(
647     post_snippet: &str,
648     separator: &str,
649     terminator: &str,
650     is_last: bool,
651 ) -> usize {
652     if is_last {
653         return post_snippet
654             .find_uncommented(terminator)
655             .unwrap_or_else(|| post_snippet.len());
656     }
657
658     let mut block_open_index = post_snippet.find("/*");
659     // check if it really is a block comment (and not `//*` or a nested comment)
660     if let Some(i) = block_open_index {
661         match post_snippet.find('/') {
662             Some(j) if j < i => block_open_index = None,
663             _ if post_snippet[..i].ends_with('/') => block_open_index = None,
664             _ => (),
665         }
666     }
667     let newline_index = post_snippet.find('\n');
668     if let Some(separator_index) = post_snippet.find_uncommented(separator) {
669         match (block_open_index, newline_index) {
670             // Separator before comment, with the next item on same line.
671             // Comment belongs to next item.
672             (Some(i), None) if i > separator_index => separator_index + 1,
673             // Block-style post-comment before the separator.
674             (Some(i), None) => cmp::max(
675                 find_comment_end(&post_snippet[i..]).unwrap() + i,
676                 separator_index + 1,
677             ),
678             // Block-style post-comment. Either before or after the separator.
679             (Some(i), Some(j)) if i < j => cmp::max(
680                 find_comment_end(&post_snippet[i..]).unwrap() + i,
681                 separator_index + 1,
682             ),
683             // Potential *single* line comment.
684             (_, Some(j)) if j > separator_index => j + 1,
685             _ => post_snippet.len(),
686         }
687     } else if let Some(newline_index) = newline_index {
688         // Match arms may not have trailing comma. In any case, for match arms,
689         // we will assume that the post comment belongs to the next arm if they
690         // do not end with trailing comma.
691         newline_index + 1
692     } else {
693         0
694     }
695 }
696
697 // Account for extra whitespace between items. This is fiddly
698 // because of the way we divide pre- and post- comments.
699 pub(crate) fn has_extra_newline(post_snippet: &str, comment_end: usize) -> bool {
700     if post_snippet.is_empty() || comment_end == 0 {
701         return false;
702     }
703
704     let len_last = post_snippet[..comment_end]
705         .chars()
706         .last()
707         .unwrap()
708         .len_utf8();
709     // Everything from the separator to the next item.
710     let test_snippet = &post_snippet[comment_end - len_last..];
711     let first_newline = test_snippet
712         .find('\n')
713         .unwrap_or_else(|| test_snippet.len());
714     // From the end of the first line of comments.
715     let test_snippet = &test_snippet[first_newline..];
716     let first = test_snippet
717         .find(|c: char| !c.is_whitespace())
718         .unwrap_or_else(|| test_snippet.len());
719     // From the end of the first line of comments to the next non-whitespace char.
720     let test_snippet = &test_snippet[..first];
721
722     // There were multiple line breaks which got trimmed to nothing.
723     count_newlines(test_snippet) > 1
724 }
725
726 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
727 where
728     I: Iterator<Item = T>,
729     F1: Fn(&T) -> BytePos,
730     F2: Fn(&T) -> BytePos,
731     F3: Fn(&T) -> Option<String>,
732 {
733     type Item = ListItem;
734
735     fn next(&mut self) -> Option<Self::Item> {
736         self.inner.next().map(|item| {
737             // Pre-comment
738             let pre_snippet = self
739                 .snippet_provider
740                 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
741                 .unwrap_or("");
742             let (pre_comment, pre_comment_style) = extract_pre_comment(pre_snippet);
743
744             // Post-comment
745             let next_start = match self.inner.peek() {
746                 Some(next_item) => (self.get_lo)(next_item),
747                 None => self.next_span_start,
748             };
749             let post_snippet = self
750                 .snippet_provider
751                 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
752                 .unwrap_or("");
753             let comment_end = get_comment_end(
754                 post_snippet,
755                 self.separator,
756                 self.terminator,
757                 self.inner.peek().is_none(),
758             );
759             let new_lines = has_extra_newline(post_snippet, comment_end);
760             let post_comment = extract_post_comment(post_snippet, comment_end, self.separator);
761
762             self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
763
764             ListItem {
765                 pre_comment,
766                 pre_comment_style,
767                 item: if self.inner.peek().is_none() && self.leave_last {
768                     None
769                 } else {
770                     (self.get_item_string)(&item)
771                 },
772                 post_comment,
773                 new_lines,
774             }
775         })
776     }
777 }
778
779 #[allow(clippy::too_many_arguments)]
780 // Creates an iterator over a list's items with associated comments.
781 pub(crate) fn itemize_list<'a, T, I, F1, F2, F3>(
782     snippet_provider: &'a SnippetProvider,
783     inner: I,
784     terminator: &'a str,
785     separator: &'a str,
786     get_lo: F1,
787     get_hi: F2,
788     get_item_string: F3,
789     prev_span_end: BytePos,
790     next_span_start: BytePos,
791     leave_last: bool,
792 ) -> ListItems<'a, I, F1, F2, F3>
793 where
794     I: Iterator<Item = T>,
795     F1: Fn(&T) -> BytePos,
796     F2: Fn(&T) -> BytePos,
797     F3: Fn(&T) -> Option<String>,
798 {
799     ListItems {
800         snippet_provider,
801         inner: inner.peekable(),
802         get_lo,
803         get_hi,
804         get_item_string,
805         prev_span_end,
806         next_span_start,
807         terminator,
808         separator,
809         leave_last,
810     }
811 }
812
813 /// Returns the count and total width of the list items.
814 fn calculate_width<I, T>(items: I) -> (usize, usize)
815 where
816     I: IntoIterator<Item = T>,
817     T: AsRef<ListItem>,
818 {
819     items
820         .into_iter()
821         .map(|item| total_item_width(item.as_ref()))
822         .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
823 }
824
825 pub(crate) fn total_item_width(item: &ListItem) -> usize {
826     comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
827         + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
828         + item.item.as_ref().map_or(0, |s| unicode_str_width(s))
829 }
830
831 fn comment_len(comment: Option<&str>) -> usize {
832     match comment {
833         Some(s) => {
834             let text_len = s.trim().len();
835             if text_len > 0 {
836                 // We'll put " /*" before and " */" after inline comments.
837                 text_len + 6
838             } else {
839                 text_len
840             }
841         }
842         None => 0,
843     }
844 }
845
846 // Compute horizontal and vertical shapes for a struct-lit-like thing.
847 pub(crate) fn struct_lit_shape(
848     shape: Shape,
849     context: &RewriteContext<'_>,
850     prefix_width: usize,
851     suffix_width: usize,
852 ) -> Option<(Option<Shape>, Shape)> {
853     let v_shape = match context.config.indent_style() {
854         IndentStyle::Visual => shape
855             .visual_indent(0)
856             .shrink_left(prefix_width)?
857             .sub_width(suffix_width)?,
858         IndentStyle::Block => {
859             let shape = shape.block_indent(context.config.tab_spaces());
860             Shape {
861                 width: context.budget(shape.indent.width()),
862                 ..shape
863             }
864         }
865     };
866     let shape_width = shape.width.checked_sub(prefix_width + suffix_width);
867     if let Some(w) = shape_width {
868         let shape_width = cmp::min(w, context.config.struct_lit_width());
869         Some((Some(Shape::legacy(shape_width, shape.indent)), v_shape))
870     } else {
871         Some((None, v_shape))
872     }
873 }
874
875 // Compute the tactic for the internals of a struct-lit-like thing.
876 pub(crate) fn struct_lit_tactic(
877     h_shape: Option<Shape>,
878     context: &RewriteContext<'_>,
879     items: &[ListItem],
880 ) -> DefinitiveListTactic {
881     if let Some(h_shape) = h_shape {
882         let prelim_tactic = match (context.config.indent_style(), items.len()) {
883             (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
884             _ if context.config.struct_lit_single_line() => ListTactic::HorizontalVertical,
885             _ => ListTactic::Vertical,
886         };
887         definitive_tactic(items, prelim_tactic, Separator::Comma, h_shape.width)
888     } else {
889         DefinitiveListTactic::Vertical
890     }
891 }
892
893 // Given a tactic and possible shapes for horizontal and vertical layout,
894 // come up with the actual shape to use.
895 pub(crate) fn shape_for_tactic(
896     tactic: DefinitiveListTactic,
897     h_shape: Option<Shape>,
898     v_shape: Shape,
899 ) -> Shape {
900     match tactic {
901         DefinitiveListTactic::Horizontal => h_shape.unwrap(),
902         _ => v_shape,
903     }
904 }
905
906 // Create a ListFormatting object for formatting the internals of a
907 // struct-lit-like thing, that is a series of fields.
908 pub(crate) fn struct_lit_formatting<'a>(
909     shape: Shape,
910     tactic: DefinitiveListTactic,
911     context: &'a RewriteContext<'_>,
912     force_no_trailing_comma: bool,
913 ) -> ListFormatting<'a> {
914     let ends_with_newline = context.config.indent_style() != IndentStyle::Visual
915         && tactic == DefinitiveListTactic::Vertical;
916     ListFormatting {
917         tactic,
918         separator: ",",
919         trailing_separator: if force_no_trailing_comma {
920             SeparatorTactic::Never
921         } else {
922             context.config.trailing_comma()
923         },
924         separator_place: SeparatorPlace::Back,
925         shape,
926         ends_with_newline,
927         preserve_newline: true,
928         nested: false,
929         align_comments: true,
930         config: context.config,
931     }
932 }