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