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