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