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