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