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