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