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