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