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