]> git.lizzy.rs Git - rust.git/blob - src/lists.rs
Merge pull request #2890 from topecongiro/use-builder-pattern-for-ListFormatting
[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::codemap::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 + 1) {
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 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
568 where
569     I: Iterator<Item = T>,
570     F1: Fn(&T) -> BytePos,
571     F2: Fn(&T) -> BytePos,
572     F3: Fn(&T) -> Option<String>,
573 {
574     type Item = ListItem;
575
576     fn next(&mut self) -> Option<Self::Item> {
577         let white_space: &[_] = &[' ', '\t'];
578
579         self.inner.next().map(|item| {
580             let mut new_lines = false;
581             // Pre-comment
582             let pre_snippet = self
583                 .snippet_provider
584                 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
585                 .unwrap_or("");
586             let trimmed_pre_snippet = pre_snippet.trim();
587             let has_single_line_comment = trimmed_pre_snippet.starts_with("//");
588             let has_block_comment = trimmed_pre_snippet.starts_with("/*");
589             let (pre_comment, pre_comment_style) = if has_single_line_comment {
590                 (
591                     Some(trimmed_pre_snippet.to_owned()),
592                     ListItemCommentStyle::DifferentLine,
593                 )
594             } else if has_block_comment {
595                 let comment_end = pre_snippet.chars().rev().position(|c| c == '/').unwrap();
596                 if pre_snippet
597                     .chars()
598                     .rev()
599                     .take(comment_end + 1)
600                     .any(|c| c == '\n')
601                 {
602                     (
603                         Some(trimmed_pre_snippet.to_owned()),
604                         ListItemCommentStyle::DifferentLine,
605                     )
606                 } else {
607                     (
608                         Some(trimmed_pre_snippet.to_owned()),
609                         ListItemCommentStyle::SameLine,
610                     )
611                 }
612             } else {
613                 (None, ListItemCommentStyle::None)
614             };
615
616             // Post-comment
617             let next_start = match self.inner.peek() {
618                 Some(next_item) => (self.get_lo)(next_item),
619                 None => self.next_span_start,
620             };
621             let post_snippet = self
622                 .snippet_provider
623                 .span_to_snippet(mk_sp((self.get_hi)(&item), next_start))
624                 .unwrap_or("");
625
626             let comment_end = match self.inner.peek() {
627                 Some(..) => {
628                     let mut block_open_index = post_snippet.find("/*");
629                     // check if it really is a block comment (and not `//*` or a nested comment)
630                     if let Some(i) = block_open_index {
631                         match post_snippet.find('/') {
632                             Some(j) if j < i => block_open_index = None,
633                             _ if i > 0 && &post_snippet[i - 1..i] == "/" => block_open_index = None,
634                             _ => (),
635                         }
636                     }
637                     let newline_index = post_snippet.find('\n');
638                     if let Some(separator_index) = post_snippet.find_uncommented(self.separator) {
639                         match (block_open_index, newline_index) {
640                             // Separator before comment, with the next item on same line.
641                             // Comment belongs to next item.
642                             (Some(i), None) if i > separator_index => separator_index + 1,
643                             // Block-style post-comment before the separator.
644                             (Some(i), None) => cmp::max(
645                                 find_comment_end(&post_snippet[i..]).unwrap() + i,
646                                 separator_index + 1,
647                             ),
648                             // Block-style post-comment. Either before or after the separator.
649                             (Some(i), Some(j)) if i < j => cmp::max(
650                                 find_comment_end(&post_snippet[i..]).unwrap() + i,
651                                 separator_index + 1,
652                             ),
653                             // Potential *single* line comment.
654                             (_, Some(j)) if j > separator_index => j + 1,
655                             _ => post_snippet.len(),
656                         }
657                     } else if let Some(newline_index) = newline_index {
658                         // Match arms may not have trailing comma. In any case, for match arms,
659                         // we will assume that the post comment belongs to the next arm if they
660                         // do not end with trailing comma.
661                         newline_index + 1
662                     } else {
663                         0
664                     }
665                 }
666                 None => post_snippet
667                     .find_uncommented(self.terminator)
668                     .unwrap_or_else(|| post_snippet.len()),
669             };
670
671             if !post_snippet.is_empty() && comment_end > 0 {
672                 // Account for extra whitespace between items. This is fiddly
673                 // because of the way we divide pre- and post- comments.
674
675                 // Everything from the separator to the next item.
676                 let test_snippet = &post_snippet[comment_end - 1..];
677                 let first_newline = test_snippet
678                     .find('\n')
679                     .unwrap_or_else(|| test_snippet.len());
680                 // From the end of the first line of comments.
681                 let test_snippet = &test_snippet[first_newline..];
682                 let first = test_snippet
683                     .find(|c: char| !c.is_whitespace())
684                     .unwrap_or_else(|| test_snippet.len());
685                 // From the end of the first line of comments to the next non-whitespace char.
686                 let test_snippet = &test_snippet[..first];
687
688                 if count_newlines(test_snippet) > 1 {
689                     // There were multiple line breaks which got trimmed to nothing.
690                     new_lines = true;
691                 }
692             }
693
694             // Cleanup post-comment: strip separators and whitespace.
695             self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
696             let post_snippet = post_snippet[..comment_end].trim();
697
698             let post_snippet_trimmed = if post_snippet.starts_with(|c| c == ',' || c == ':') {
699                 post_snippet[1..].trim_matches(white_space)
700             } else if post_snippet.starts_with(self.separator) {
701                 post_snippet[self.separator.len()..].trim_matches(white_space)
702             } else if post_snippet.ends_with(',') {
703                 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
704             } else {
705                 post_snippet
706             };
707
708             let post_comment = if !post_snippet_trimmed.is_empty() {
709                 Some(post_snippet_trimmed.to_owned())
710             } else {
711                 None
712             };
713
714             ListItem {
715                 pre_comment,
716                 pre_comment_style,
717                 item: if self.inner.peek().is_none() && self.leave_last {
718                     None
719                 } else {
720                     (self.get_item_string)(&item)
721                 },
722                 post_comment,
723                 new_lines,
724             }
725         })
726     }
727 }
728
729 #[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
730 // Creates an iterator over a list's items with associated comments.
731 pub fn itemize_list<'a, T, I, F1, F2, F3>(
732     snippet_provider: &'a SnippetProvider,
733     inner: I,
734     terminator: &'a str,
735     separator: &'a str,
736     get_lo: F1,
737     get_hi: F2,
738     get_item_string: F3,
739     prev_span_end: BytePos,
740     next_span_start: BytePos,
741     leave_last: bool,
742 ) -> ListItems<'a, I, F1, F2, F3>
743 where
744     I: Iterator<Item = T>,
745     F1: Fn(&T) -> BytePos,
746     F2: Fn(&T) -> BytePos,
747     F3: Fn(&T) -> Option<String>,
748 {
749     ListItems {
750         snippet_provider,
751         inner: inner.peekable(),
752         get_lo,
753         get_hi,
754         get_item_string,
755         prev_span_end,
756         next_span_start,
757         terminator,
758         separator,
759         leave_last,
760     }
761 }
762
763 /// Returns the count and total width of the list items.
764 fn calculate_width<I, T>(items: I) -> (usize, usize)
765 where
766     I: IntoIterator<Item = T>,
767     T: AsRef<ListItem>,
768 {
769     items
770         .into_iter()
771         .map(|item| total_item_width(item.as_ref()))
772         .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
773 }
774
775 pub fn total_item_width(item: &ListItem) -> usize {
776     comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
777         + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
778         + item.item.as_ref().map_or(0, |str| str.len())
779 }
780
781 fn comment_len(comment: Option<&str>) -> usize {
782     match comment {
783         Some(s) => {
784             let text_len = s.trim().len();
785             if text_len > 0 {
786                 // We'll put " /*" before and " */" after inline comments.
787                 text_len + 6
788             } else {
789                 text_len
790             }
791         }
792         None => 0,
793     }
794 }
795
796 // Compute horizontal and vertical shapes for a struct-lit-like thing.
797 pub fn struct_lit_shape(
798     shape: Shape,
799     context: &RewriteContext,
800     prefix_width: usize,
801     suffix_width: usize,
802 ) -> Option<(Option<Shape>, Shape)> {
803     let v_shape = match context.config.indent_style() {
804         IndentStyle::Visual => shape
805             .visual_indent(0)
806             .shrink_left(prefix_width)?
807             .sub_width(suffix_width)?,
808         IndentStyle::Block => {
809             let shape = shape.block_indent(context.config.tab_spaces());
810             Shape {
811                 width: context.budget(shape.indent.width()),
812                 ..shape
813             }
814         }
815     };
816     let shape_width = shape.width.checked_sub(prefix_width + suffix_width);
817     if let Some(w) = shape_width {
818         let shape_width = cmp::min(w, context.config.width_heuristics().struct_lit_width);
819         Some((Some(Shape::legacy(shape_width, shape.indent)), v_shape))
820     } else {
821         Some((None, v_shape))
822     }
823 }
824
825 // Compute the tactic for the internals of a struct-lit-like thing.
826 pub fn struct_lit_tactic(
827     h_shape: Option<Shape>,
828     context: &RewriteContext,
829     items: &[ListItem],
830 ) -> DefinitiveListTactic {
831     if let Some(h_shape) = h_shape {
832         let prelim_tactic = match (context.config.indent_style(), items.len()) {
833             (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
834             _ if context.config.struct_lit_single_line() => ListTactic::HorizontalVertical,
835             _ => ListTactic::Vertical,
836         };
837         definitive_tactic(items, prelim_tactic, Separator::Comma, h_shape.width)
838     } else {
839         DefinitiveListTactic::Vertical
840     }
841 }
842
843 // Given a tactic and possible shapes for horizontal and vertical layout,
844 // come up with the actual shape to use.
845 pub fn shape_for_tactic(
846     tactic: DefinitiveListTactic,
847     h_shape: Option<Shape>,
848     v_shape: Shape,
849 ) -> Shape {
850     match tactic {
851         DefinitiveListTactic::Horizontal => h_shape.unwrap(),
852         _ => v_shape,
853     }
854 }
855
856 // Create a ListFormatting object for formatting the internals of a
857 // struct-lit-like thing, that is a series of fields.
858 pub fn struct_lit_formatting<'a>(
859     shape: Shape,
860     tactic: DefinitiveListTactic,
861     context: &'a RewriteContext,
862     force_no_trailing_comma: bool,
863 ) -> ListFormatting<'a> {
864     let ends_with_newline = context.config.indent_style() != IndentStyle::Visual
865         && tactic == DefinitiveListTactic::Vertical;
866     ListFormatting {
867         tactic,
868         separator: ",",
869         trailing_separator: if force_no_trailing_comma {
870             SeparatorTactic::Never
871         } else {
872             context.config.trailing_comma()
873         },
874         separator_place: SeparatorPlace::Back,
875         shape,
876         ends_with_newline,
877         preserve_newline: true,
878         nested: false,
879         config: context.config,
880     }
881 }