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