]> git.lizzy.rs Git - rust.git/blob - src/lists.rs
Use write_list() for rewriting match arms
[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 use std::cmp;
12 use std::iter::Peekable;
13
14 use syntax::codemap::{BytePos, CodeMap};
15
16 use {Indent, Shape};
17 use comment::{find_comment_end, rewrite_comment, FindUncommented};
18 use config::{Config, IndentStyle};
19 use rewrite::RewriteContext;
20 use utils::{first_line_width, last_line_width, mk_sp};
21
22 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
23 /// Formatting tactic for lists. This will be cast down to a
24 /// DefinitiveListTactic depending on the number and length of the items and
25 /// their comments.
26 pub enum ListTactic {
27     // One item per row.
28     Vertical,
29     // All items on one row.
30     Horizontal,
31     // Try Horizontal layout, if that fails then vertical.
32     HorizontalVertical,
33     // HorizontalVertical with a soft limit of n characters.
34     LimitedHorizontalVertical(usize),
35     // Pack as many items as possible per row over (possibly) many rows.
36     Mixed,
37 }
38
39 impl_enum_serialize_and_deserialize!(ListTactic, Vertical, Horizontal, HorizontalVertical, Mixed);
40
41 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
42 pub enum SeparatorTactic {
43     Always,
44     Never,
45     Vertical,
46 }
47
48 impl_enum_serialize_and_deserialize!(SeparatorTactic, Always, Never, Vertical);
49
50 impl SeparatorTactic {
51     pub fn from_bool(b: bool) -> SeparatorTactic {
52         if b {
53             SeparatorTactic::Always
54         } else {
55             SeparatorTactic::Never
56         }
57     }
58 }
59
60 pub struct ListFormatting<'a> {
61     pub tactic: DefinitiveListTactic,
62     pub separator: &'a str,
63     pub trailing_separator: SeparatorTactic,
64     pub shape: Shape,
65     // Non-expressions, e.g. items, will have a new line at the end of the list.
66     // Important for comment styles.
67     pub ends_with_newline: bool,
68     // Remove newlines between list elements for expressions.
69     pub preserve_newline: bool,
70     pub config: &'a Config,
71 }
72
73 impl AsRef<ListItem> for ListItem {
74     fn as_ref(&self) -> &ListItem {
75         self
76     }
77 }
78
79 #[derive(PartialEq, Eq)]
80 pub enum ListItemCommentStyle {
81     // Try to keep the comment on the same line with the item.
82     SameLine,
83     // Put the comment on the previous or the next line of the item.
84     DifferentLine,
85     // No comment available.
86     None,
87 }
88
89 pub struct ListItem {
90     // None for comments mean that they are not present.
91     pub pre_comment: Option<String>,
92     pub pre_comment_style: ListItemCommentStyle,
93     // Item should include attributes and doc comments. None indicates a failed
94     // rewrite.
95     pub item: Option<String>,
96     pub post_comment: Option<String>,
97     // Whether there is extra whitespace before this item.
98     pub new_lines: bool,
99 }
100
101 impl ListItem {
102     pub fn inner_as_ref(&self) -> &str {
103         self.item.as_ref().map_or("", |s| &*s)
104     }
105
106     pub fn is_multiline(&self) -> bool {
107         self.inner_as_ref().contains('\n') || self.pre_comment.is_some() ||
108             self.post_comment
109                 .as_ref()
110                 .map_or(false, |s| s.contains('\n'))
111     }
112
113     pub fn has_comment(&self) -> bool {
114         self.pre_comment
115             .as_ref()
116             .map_or(false, |comment| comment.starts_with("//")) ||
117             self.post_comment
118                 .as_ref()
119                 .map_or(false, |comment| comment.starts_with("//"))
120     }
121
122     pub fn from_str<S: Into<String>>(s: S) -> ListItem {
123         ListItem {
124             pre_comment: None,
125             pre_comment_style: ListItemCommentStyle::None,
126             item: Some(s.into()),
127             post_comment: None,
128             new_lines: false,
129         }
130     }
131 }
132
133 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
134 /// The definitive formatting tactic for lists.
135 pub enum DefinitiveListTactic {
136     Vertical,
137     Horizontal,
138     Mixed,
139 }
140
141 impl DefinitiveListTactic {
142     pub fn ends_with_newline(&self, indent_style: IndentStyle) -> bool {
143         match indent_style {
144             IndentStyle::Block => *self != DefinitiveListTactic::Horizontal,
145             IndentStyle::Visual => false,
146         }
147     }
148 }
149
150 /// The type of separator for lists.
151 #[derive(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_comment());
182
183     let limit = match tactic {
184         _ if pre_line_comments => return DefinitiveListTactic::Vertical,
185         ListTactic::Mixed => return DefinitiveListTactic::Mixed,
186         ListTactic::Horizontal => return DefinitiveListTactic::Horizontal,
187         ListTactic::Vertical => return DefinitiveListTactic::Vertical,
188         ListTactic::LimitedHorizontalVertical(limit) => ::std::cmp::min(width, limit),
189         ListTactic::HorizontalVertical => width,
190     };
191
192     let (sep_count, total_width) = calculate_width(items.clone());
193     let total_sep_len = sep.len() * sep_count.checked_sub(1).unwrap_or(0);
194     let real_total = total_width + total_sep_len;
195
196     if real_total <= limit && !pre_line_comments &&
197         !items.into_iter().any(|item| item.as_ref().is_multiline())
198     {
199         DefinitiveListTactic::Horizontal
200     } else {
201         DefinitiveListTactic::Vertical
202     }
203 }
204
205 // Format a list of commented items into a string.
206 // TODO: add unit tests
207 pub fn write_list<I, T>(items: I, formatting: &ListFormatting) -> Option<String>
208 where
209     I: IntoIterator<Item = T> + Clone,
210     T: AsRef<ListItem>,
211 {
212     let tactic = formatting.tactic;
213     let sep_len = formatting.separator.len();
214
215     // Now that we know how we will layout, we can decide for sure if there
216     // will be a trailing separator.
217     let mut trailing_separator = needs_trailing_separator(formatting.trailing_separator, tactic);
218     let mut result = String::new();
219     let cloned_items = items.clone();
220     let mut iter = items.into_iter().enumerate().peekable();
221     let mut item_max_width: Option<usize> = None;
222
223     let mut line_len = 0;
224     let indent_str = &formatting.shape.indent.to_string(formatting.config);
225     while let Some((i, item)) = iter.next() {
226         let item = item.as_ref();
227         let inner_item = try_opt!(item.item.as_ref());
228         let first = i == 0;
229         let last = iter.peek().is_none();
230         let mut separate = !last || trailing_separator;
231         let item_sep_len = if separate { sep_len } else { 0 };
232
233         // Item string may be multi-line. Its length (used for block comment alignment)
234         // should be only the length of the last line.
235         let item_last_line = if item.is_multiline() {
236             inner_item.lines().last().unwrap_or("")
237         } else {
238             inner_item.as_ref()
239         };
240         let mut item_last_line_width = item_last_line.len() + item_sep_len;
241         if item_last_line.starts_with(indent_str) {
242             item_last_line_width -= indent_str.len();
243         }
244
245         match tactic {
246             DefinitiveListTactic::Horizontal if !first => {
247                 result.push(' ');
248             }
249             DefinitiveListTactic::Vertical if !first => {
250                 result.push('\n');
251                 result.push_str(indent_str);
252             }
253             DefinitiveListTactic::Mixed => {
254                 let total_width = total_item_width(item) + item_sep_len;
255
256                 // 1 is space between separator and item.
257                 if line_len > 0 && line_len + 1 + total_width > formatting.shape.width {
258                     result.push('\n');
259                     result.push_str(indent_str);
260                     line_len = 0;
261                     if tactic == DefinitiveListTactic::Mixed && formatting.ends_with_newline {
262                         if last {
263                             separate = true;
264                         } else {
265                             trailing_separator = true;
266                         }
267                     }
268                 }
269
270                 if line_len > 0 {
271                     result.push(' ');
272                     line_len += 1;
273                 }
274
275                 line_len += total_width;
276             }
277             _ => {}
278         }
279
280         // Pre-comments
281         if let Some(ref comment) = item.pre_comment {
282             // Block style in non-vertical mode.
283             let block_mode = tactic != DefinitiveListTactic::Vertical;
284             // Width restriction is only relevant in vertical mode.
285             let comment = try_opt!(rewrite_comment(
286                 comment,
287                 block_mode,
288                 formatting.shape,
289                 formatting.config,
290             ));
291             result.push_str(&comment);
292
293             if tactic == DefinitiveListTactic::Vertical {
294                 // We cannot keep pre-comments on the same line if the comment if normalized.
295                 let keep_comment = if formatting.config.normalize_comments() {
296                     false
297                 } else if item.pre_comment_style == ListItemCommentStyle::DifferentLine {
298                     false
299                 } else {
300                     // We will try to keep the comment on the same line with the item here.
301                     // 1 = ` `
302                     let total_width = total_item_width(item) + item_sep_len + 1;
303                     total_width <= formatting.shape.width
304                 };
305                 if keep_comment {
306                     result.push(' ');
307                 } else {
308                     result.push('\n');
309                     result.push_str(indent_str);
310                 }
311             } else {
312                 result.push(' ');
313             }
314             item_max_width = None;
315         }
316
317         result.push_str(&inner_item[..]);
318
319         // Post-comments
320         if tactic != DefinitiveListTactic::Vertical && item.post_comment.is_some() {
321             let comment = item.post_comment.as_ref().unwrap();
322             let formatted_comment = try_opt!(rewrite_comment(
323                 comment,
324                 true,
325                 Shape::legacy(formatting.shape.width, Indent::empty()),
326                 formatting.config,
327             ));
328
329             result.push(' ');
330             result.push_str(&formatted_comment);
331         }
332
333         if separate {
334             result.push_str(formatting.separator);
335         }
336
337         if tactic == DefinitiveListTactic::Vertical && item.post_comment.is_some() {
338             let comment = item.post_comment.as_ref().unwrap();
339             let overhead = last_line_width(&result) + first_line_width(comment.trim());
340
341             let rewrite_post_comment = |item_max_width: &mut Option<usize>| {
342                 if item_max_width.is_none() && !last && !inner_item.contains('\n') {
343                     *item_max_width = Some(max_width_of_item_with_post_comment(
344                         &cloned_items,
345                         i,
346                         overhead,
347                         formatting.config.max_width(),
348                     ));
349                 }
350                 let overhead = if let &mut Some(max_width) = item_max_width {
351                     max_width + 2
352                 } else {
353                     // 1 = space between item and comment.
354                     item_last_line_width + 1
355                 };
356                 let width = formatting.shape.width.checked_sub(overhead).unwrap_or(1);
357                 let offset = formatting.shape.indent + overhead;
358                 let comment_shape = Shape::legacy(width, offset);
359
360                 // Use block-style only for the last item or multiline comments.
361                 let block_style = !formatting.ends_with_newline && last ||
362                     comment.trim().contains('\n') ||
363                     comment.trim().len() > width;
364
365                 rewrite_comment(comment, block_style, comment_shape, formatting.config)
366             };
367
368             let mut formatted_comment = try_opt!(rewrite_post_comment(&mut item_max_width));
369
370             if !formatted_comment.starts_with('\n') {
371                 let mut comment_alignment =
372                     post_comment_alignment(item_max_width, inner_item.len());
373                 if first_line_width(&formatted_comment) + last_line_width(&result) +
374                     comment_alignment + 1 > formatting.config.max_width()
375                 {
376                     item_max_width = None;
377                     formatted_comment = try_opt!(rewrite_post_comment(&mut item_max_width));
378                     comment_alignment = post_comment_alignment(item_max_width, inner_item.len());
379                 }
380                 for _ in 0..(comment_alignment + 1) {
381                     result.push(' ');
382                 }
383                 // An additional space for the missing trailing separator.
384                 if last && item_max_width.is_some() && !separate && !formatting.separator.is_empty()
385                 {
386                     result.push(' ');
387                 }
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_multiline() || !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     codemap: &'a CodeMap,
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     leave_last: bool,
459 }
460
461 impl<'a, T, I, F1, F2, F3> Iterator for ListItems<'a, I, F1, F2, F3>
462 where
463     I: Iterator<Item = T>,
464     F1: Fn(&T) -> BytePos,
465     F2: Fn(&T) -> BytePos,
466     F3: Fn(&T) -> Option<String>,
467 {
468     type Item = ListItem;
469
470     fn next(&mut self) -> Option<Self::Item> {
471         let white_space: &[_] = &[' ', '\t'];
472
473         self.inner.next().map(|item| {
474             let mut new_lines = false;
475             // Pre-comment
476             let pre_snippet = self.codemap
477                 .span_to_snippet(mk_sp(self.prev_span_end, (self.get_lo)(&item)))
478                 .unwrap();
479             let trimmed_pre_snippet = pre_snippet.trim();
480             let has_single_line_comment = trimmed_pre_snippet.starts_with("//");
481             let has_block_comment = trimmed_pre_snippet.starts_with("/*");
482             let (pre_comment, pre_comment_style) = if has_single_line_comment {
483                 (
484                     Some(trimmed_pre_snippet.to_owned()),
485                     ListItemCommentStyle::DifferentLine,
486                 )
487             } else if has_block_comment {
488                 let comment_end = pre_snippet.chars().rev().position(|c| c == '/').unwrap();
489                 if pre_snippet
490                     .chars()
491                     .rev()
492                     .take(comment_end + 1)
493                     .find(|c| *c == '\n')
494                     .is_some()
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.codemap
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 realy is a block comment (and not //*)
523                     if let Some(i) = block_open_index {
524                         if i > 0 && &post_snippet[i - 1..i] == "/" {
525                             block_open_index = None;
526                         }
527                     }
528                     let newline_index = post_snippet.find('\n');
529                     if let Some(separator_index) = post_snippet.find_uncommented(",") {
530                         match (block_open_index, newline_index) {
531                             // Separator before comment, with the next item on same line.
532                             // Comment belongs to next item.
533                             (Some(i), None) if i > separator_index => separator_index + 1,
534                             // Block-style post-comment before the separator.
535                             (Some(i), None) => cmp::max(
536                                 find_comment_end(&post_snippet[i..]).unwrap() + i,
537                                 separator_index + 1,
538                             ),
539                             // Block-style post-comment. Either before or after the separator.
540                             (Some(i), Some(j)) if i < j => cmp::max(
541                                 find_comment_end(&post_snippet[i..]).unwrap() + i,
542                                 separator_index + 1,
543                             ),
544                             // Potential *single* line comment.
545                             (_, Some(j)) if j > separator_index => j + 1,
546                             _ => post_snippet.len(),
547                         }
548                     } else {
549                         // Match arms may not have trailing comma. In any case, for match arms,
550                         // we will assume that the post comment belongs to the next arm if they
551                         // do not end with trailing comma.
552                         1
553                     }
554                 }
555                 None => post_snippet
556                     .find_uncommented(self.terminator)
557                     .unwrap_or(post_snippet.len()),
558             };
559
560             if !post_snippet.is_empty() && comment_end > 0 {
561                 // Account for extra whitespace between items. This is fiddly
562                 // because of the way we divide pre- and post- comments.
563
564                 // Everything from the separator to the next item.
565                 let test_snippet = &post_snippet[comment_end - 1..];
566                 let first_newline = test_snippet.find('\n').unwrap_or(test_snippet.len());
567                 // From the end of the first line of comments.
568                 let test_snippet = &test_snippet[first_newline..];
569                 let first = test_snippet
570                     .find(|c: char| !c.is_whitespace())
571                     .unwrap_or(test_snippet.len());
572                 // From the end of the first line of comments to the next non-whitespace char.
573                 let test_snippet = &test_snippet[..first];
574
575                 if test_snippet.chars().filter(|c| c == &'\n').count() > 1 {
576                     // There were multiple line breaks which got trimmed to nothing.
577                     new_lines = true;
578                 }
579             }
580
581             // Cleanup post-comment: strip separators and whitespace.
582             self.prev_span_end = (self.get_hi)(&item) + BytePos(comment_end as u32);
583             let post_snippet = post_snippet[..comment_end].trim();
584
585             let post_snippet_trimmed = if post_snippet.starts_with(',') {
586                 post_snippet[1..].trim_matches(white_space)
587             } else if post_snippet.ends_with(',') {
588                 post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
589             } else {
590                 post_snippet
591             };
592
593             let post_comment = if !post_snippet_trimmed.is_empty() {
594                 Some(post_snippet_trimmed.to_owned())
595             } else {
596                 None
597             };
598
599             ListItem {
600                 pre_comment: pre_comment,
601                 pre_comment_style: pre_comment_style,
602                 item: if self.inner.peek().is_none() && self.leave_last {
603                     None
604                 } else {
605                     (self.get_item_string)(&item)
606                 },
607                 post_comment: post_comment,
608                 new_lines: new_lines,
609             }
610         })
611     }
612 }
613
614 // Creates an iterator over a list's items with associated comments.
615 pub fn itemize_list<'a, T, I, F1, F2, F3>(
616     codemap: &'a CodeMap,
617     inner: I,
618     terminator: &'a str,
619     get_lo: F1,
620     get_hi: F2,
621     get_item_string: F3,
622     prev_span_end: BytePos,
623     next_span_start: BytePos,
624     leave_last: bool,
625 ) -> ListItems<'a, I, F1, F2, F3>
626 where
627     I: Iterator<Item = T>,
628     F1: Fn(&T) -> BytePos,
629     F2: Fn(&T) -> BytePos,
630     F3: Fn(&T) -> Option<String>,
631 {
632     ListItems {
633         codemap: codemap,
634         inner: inner.peekable(),
635         get_lo: get_lo,
636         get_hi: get_hi,
637         get_item_string: get_item_string,
638         prev_span_end: prev_span_end,
639         next_span_start: next_span_start,
640         terminator: terminator,
641         leave_last: leave_last,
642     }
643 }
644
645 fn needs_trailing_separator(
646     separator_tactic: SeparatorTactic,
647     list_tactic: DefinitiveListTactic,
648 ) -> bool {
649     match separator_tactic {
650         SeparatorTactic::Always => true,
651         SeparatorTactic::Vertical => list_tactic == DefinitiveListTactic::Vertical,
652         SeparatorTactic::Never => false,
653     }
654 }
655
656 /// Returns the count and total width of the list items.
657 fn calculate_width<I, T>(items: I) -> (usize, usize)
658 where
659     I: IntoIterator<Item = T>,
660     T: AsRef<ListItem>,
661 {
662     items
663         .into_iter()
664         .map(|item| total_item_width(item.as_ref()))
665         .fold((0, 0), |acc, l| (acc.0 + 1, acc.1 + l))
666 }
667
668 fn total_item_width(item: &ListItem) -> usize {
669     comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..])) +
670         comment_len(item.post_comment.as_ref().map(|x| &(*x)[..])) +
671         item.item.as_ref().map_or(0, |str| str.len())
672 }
673
674 fn comment_len(comment: Option<&str>) -> usize {
675     match comment {
676         Some(s) => {
677             let text_len = s.trim().len();
678             if text_len > 0 {
679                 // We'll put " /*" before and " */" after inline comments.
680                 text_len + 6
681             } else {
682                 text_len
683             }
684         }
685         None => 0,
686     }
687 }
688
689 // Compute horizontal and vertical shapes for a struct-lit-like thing.
690 pub fn struct_lit_shape(
691     shape: Shape,
692     context: &RewriteContext,
693     prefix_width: usize,
694     suffix_width: usize,
695 ) -> Option<(Option<Shape>, Shape)> {
696     let v_shape = match context.config.struct_lit_style() {
697         IndentStyle::Visual => try_opt!(
698             try_opt!(shape.visual_indent(0).shrink_left(prefix_width)).sub_width(suffix_width)
699         ),
700         IndentStyle::Block => {
701             let shape = shape.block_indent(context.config.tab_spaces());
702             Shape {
703                 width: try_opt!(context.config.max_width().checked_sub(shape.indent.width())),
704                 ..shape
705             }
706         }
707     };
708     let shape_width = shape.width.checked_sub(prefix_width + suffix_width);
709     if let Some(w) = shape_width {
710         let shape_width = cmp::min(w, context.config.struct_lit_width());
711         Some((Some(Shape::legacy(shape_width, shape.indent)), v_shape))
712     } else {
713         Some((None, v_shape))
714     }
715 }
716
717 // Compute the tactic for the internals of a struct-lit-like thing.
718 pub fn struct_lit_tactic(
719     h_shape: Option<Shape>,
720     context: &RewriteContext,
721     items: &[ListItem],
722 ) -> DefinitiveListTactic {
723     if let Some(h_shape) = h_shape {
724         let prelim_tactic = match (context.config.struct_lit_style(), items.len()) {
725             (IndentStyle::Visual, 1) => ListTactic::HorizontalVertical,
726             _ => context.config.struct_lit_multiline_style().to_list_tactic(),
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.struct_lit_style() != IndentStyle::Visual &&
756         tactic == DefinitiveListTactic::Vertical;
757     ListFormatting {
758         tactic: tactic,
759         separator: ",",
760         trailing_separator: if force_no_trailing_comma {
761             SeparatorTactic::Never
762         } else {
763             context.config.trailing_comma()
764         },
765         shape: shape,
766         ends_with_newline: ends_with_newline,
767         preserve_newline: true,
768         config: context.config,
769     }
770 }