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