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