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