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