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