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