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