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