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