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