]> git.lizzy.rs Git - rust.git/blob - src/missed_spans.rs
Avoid adding an extra newline after block comments
[rust.git] / src / missed_spans.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 WriteMode;
12 use visitor::FmtVisitor;
13 use syntax::codemap::{self, BytePos, Span, Pos};
14 use comment::{CodeCharKind, CommentCodeSlices, rewrite_comment};
15
16 impl<'a> FmtVisitor<'a> {
17     // TODO these format_missing methods are ugly. Refactor and add unit tests
18     // for the central whitespace stripping loop.
19     pub fn format_missing(&mut self, end: BytePos) {
20         self.format_missing_inner(end,
21                                   |this, last_snippet, _| this.buffer.push_str(last_snippet))
22     }
23
24     pub fn format_missing_with_indent(&mut self, end: BytePos) {
25         let config = self.config;
26         self.format_missing_inner(end, |this, last_snippet, snippet| {
27             this.buffer.push_str(last_snippet.trim_right());
28             if last_snippet == snippet {
29                 // No new lines in the snippet.
30                 this.buffer.push_str("\n");
31             }
32             let indent = this.block_indent.to_string(config);
33             this.buffer.push_str(&indent);
34         })
35     }
36
37     fn format_missing_inner<F: Fn(&mut FmtVisitor, &str, &str)>(&mut self,
38                                                                 end: BytePos,
39                                                                 process_last_snippet: F) {
40         let start = self.last_pos;
41
42         if start == end {
43             // Do nothing if this is the beginning of the file.
44             if start != self.codemap.lookup_char_pos(start).file.start_pos {
45                 process_last_snippet(self, "", "");
46             }
47             return;
48         }
49
50         assert!(start < end,
51                 "Request to format inverted span: {:?} to {:?}",
52                 self.codemap.lookup_char_pos(start),
53                 self.codemap.lookup_char_pos(end));
54
55         self.last_pos = end;
56         let span = codemap::mk_sp(start, end);
57
58         self.write_snippet(span, &process_last_snippet);
59     }
60
61     fn write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
62         where F: Fn(&mut FmtVisitor, &str, &str)
63     {
64         // Get a snippet from the file start to the span's hi without allocating.
65         // We need it to determine what precedes the current comment. If the comment
66         // follows code on the same line, we won't touch it.
67         let big_span_lo = self.codemap.lookup_char_pos(span.lo).file.start_pos;
68         let local_begin = self.codemap.lookup_byte_offset(big_span_lo);
69         let local_end = self.codemap.lookup_byte_offset(span.hi);
70         let start_index = local_begin.pos.to_usize();
71         let end_index = local_end.pos.to_usize();
72         let big_snippet = &local_begin.fm.src.as_ref().unwrap()[start_index..end_index];
73
74         let big_diff = (span.lo - big_span_lo).to_usize();
75         let snippet = self.snippet(span);
76
77         self.write_snippet_inner(big_snippet, big_diff, &snippet, process_last_snippet);
78     }
79
80     fn write_snippet_inner<F>(&mut self,
81                               big_snippet: &str,
82                               big_diff: usize,
83                               old_snippet: &str,
84                               process_last_snippet: F)
85         where F: Fn(&mut FmtVisitor, &str, &str)
86     {
87         // Trim whitespace from the right hand side of each line.
88         // Annoyingly, the library functions for splitting by lines etc. are not
89         // quite right, so we must do it ourselves.
90         let mut line_start = 0;
91         let mut last_wspace = None;
92         let mut rewrite_next_comment = true;
93
94         fn replace_chars(string: &str) -> String {
95             string.chars()
96                   .map(|ch| {
97                       match ch.is_whitespace() {
98                           true => ch,
99                           false => 'X',
100                       }
101                   })
102                   .collect()
103         }
104
105         let replaced = match self.write_mode {
106             Some(mode) => match mode {
107                 WriteMode::Coverage => replace_chars(old_snippet),
108                 _ => old_snippet.to_owned(),
109             },
110             None => old_snippet.to_owned(),
111         };
112         let snippet = &*replaced;
113
114         for (kind, offset, subslice) in CommentCodeSlices::new(snippet) {
115             if let CodeCharKind::Comment = kind {
116                 let last_char = big_snippet[..(offset + big_diff)]
117                                     .chars()
118                                     .rev()
119                                     .skip_while(|rev_c| [' ', '\t'].contains(&rev_c))
120                                     .next();
121
122                 let fix_indent = last_char.map(|rev_c| ['{', '\n'].contains(&rev_c))
123                                           .unwrap_or(true);
124
125                 if rewrite_next_comment && fix_indent {
126                     if let Some('{') = last_char {
127                         self.buffer.push_str("\n");
128                     }
129
130                     let comment_width = ::std::cmp::min(self.config.ideal_width,
131                                                         self.config.max_width -
132                                                         self.block_indent.width());
133
134                     self.buffer.push_str(&self.block_indent.to_string(self.config));
135                     self.buffer.push_str(&rewrite_comment(subslice,
136                                                           false,
137                                                           comment_width,
138                                                           self.block_indent,
139                                                           self.config)
140                                               .unwrap());
141
142                     last_wspace = None;
143                     line_start = offset + subslice.len();
144
145                     if let Some('/') = subslice.chars().skip(1).next() {
146                         // Add a newline after line comments
147                         self.buffer.push_str("\n");
148                     } else if line_start < snippet.len() {
149                         // For other comments add a newline if there isn't one at the end already
150                         let c = snippet[line_start..].chars().next().unwrap();
151                         if c != '\n' && c != '\r' {
152                             self.buffer.push_str("\n");
153                         }
154                     }
155
156                     continue;
157                 } else {
158                     rewrite_next_comment = false;
159                 }
160             }
161
162             for (mut i, c) in subslice.char_indices() {
163                 i += offset;
164
165                 if c == '\n' {
166                     if let Some(lw) = last_wspace {
167                         self.buffer.push_str(&snippet[line_start..lw]);
168                         self.buffer.push_str("\n");
169                     } else {
170                         self.buffer.push_str(&snippet[line_start..i + 1]);
171                     }
172
173                     line_start = i + 1;
174                     last_wspace = None;
175                     rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
176                 } else {
177                     if c.is_whitespace() {
178                         if last_wspace.is_none() {
179                             last_wspace = Some(i);
180                         }
181                     } else {
182                         rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
183                         last_wspace = None;
184                     }
185                 }
186             }
187         }
188
189         process_last_snippet(self, &snippet[line_start..], &snippet);
190     }
191 }