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